在android中将时间戳转换为当前日期

时间:2023-04-06
本文介绍了在android中将时间戳转换为当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在显示日期时遇到问题,我得到的时间戳为 1379487711,但据此实际时间是 2013 年 9 月 18 日下午 12:31:51,但它显示的时间为 1970 年 17 月 41 日.如何显示为当前时间.

I have a problem in displaying the date,I am getting timestamp as 1379487711 but as per this the actual time is 9/18/2013 12:31:51 PM but it displays the time as 17-41-1970. How to show it as current time.

为了显示时间,我使用了以下方法:

for displaying time I have used the following method:

private String getDate(long milliSeconds) {
    // Create a DateFormatter object for displaying date in specified
    // format.
    SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
    // Create a calendar object that will convert the date and time value in
    // milliseconds to date.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis((int) milliSeconds);
    return formatter.format(calendar.getTime());
} 

推荐答案

private String getDate(long time) {
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(time * 1000);
    String date = DateFormat.format("dd-MM-yyyy", cal).toString();
    return date;
}

注意我把时间放在 setTimeInMillis 中,而不是 int,注意我的日期格式是 MM 而不是 mm(mm 是分钟,而不是月,这就是为什么你有一个月份应该是41"的值)

notice that I put the time in setTimeInMillis as long and not as int, notice my date format has MM and not mm (mm is for minutes, and not months, this is why you have a value of "41" where the months should be)

对于 Kotlin 用户:

fun getDate(timestamp: Long) :String {
   val calendar = Calendar.getInstance(Locale.ENGLISH)
   calendar.timeInMillis = timestamp * 1000L
   val date = DateFormat.format("dd-MM-yyyy",calendar).toString()
   return date
}

不要删除的评论:试图编辑这篇文章的亲爱的人 - 我认为完全改变答案的内容是违反本网站的行为规则的.今后请不要这样做.-LenaBru

COMMENT TO NOT BE REMOVED: Dear Person who tries to edit this post - completely changing the content of the answer is, I believe, against the conduct rules of this site. Please refrain from doing so in the future. -LenaBru

这篇关于在android中将时间戳转换为当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:在将 Java 日期写入 SQL TIMESTAMP 列之前,JDBC 是否会将日期从 JVM 时区转换为数据库会话时区 下一篇:时间戳值不正确 - c.getTimeInMills()

相关文章