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

2022-01-13 00:00:00 timestamp date android java

我在显示日期时遇到问题,我得到的时间戳为 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

相关文章