有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将毫秒转换为日期字符串

我尝试将毫秒转换为日期字符串。然而,结果并不像我预期的那样正确

输入为毫秒(例如:1508206600485

我的时区是UTC +10:00

------Expected-------------------------------------------- Actual------

01:32 (PM) 17/10/2017--------------------------------02:32 (PM) 17/10/2017

以下是方法

public static String getDate(long milliSeconds) {
    SimpleDateFormat formatter = new SimpleDateFormat("hh:mm dd/MM/yyyy");
    String dateString = formatter.format(new Date(milliSeconds));
    return dateString;
}

共 (1) 个答案

  1. # 1 楼答案

    很好you found a solution,我只想添加一个使用Java8new java.time API的方法。旧类(DateCalendarSimpleDateFormat)有lots of problemsdesign issues,如果可能,强烈建议切换到新的API

    如果您使用的是Java<;=7,您可以使用ThreeTen Backport,这是Java 8新的日期/时间类的一个很好的后台端口。对于Android,您还需要ThreeTenABP(更多关于如何使用它的信息here

    下面的代码适用于这两种情况。 唯一的区别是包名(在Java 8中是^{),在ThreeTen Backport(或Android的ThreeTenABP)中是^{),但类和方法的名称是相同的

    要将毫秒值转换为特定时区,可以使用Instant类,然后使用ZoneId转换为时区,创建ZonedDateTime。 然后使用DateTimeFormatter对其进行格式化:

    // convert millis value to a timezone
    Instant instant = Instant.ofEpochMilli(1508206600485L);
    ZonedDateTime z = instant.atZone(ZoneId.of("Australia/Sydney"));
    // format it
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm dd/MM/yyyy");
    System.out.println(fmt.format(z)); // 01:16 17/10/2017
    

    输出为:

    01:16 17/10/2017

    请注意,我使用了hh表示小时数According to javadoc,这个字母n代表am pm字段的时钟小时(值从1到12),因此如果没有am/pm指示器,它可能会不明确。也许您想添加AM/PM字段(将字母a添加到格式模式中),或者将小时数更改为HHhour of day,值从0到23)

    还要注意ZonedDateTime的实际值是2017-10-17T13:16:40.485+11:0001:16 PM),因为在2017年10月17日th,Sydney is in Daylight Saving Time,所以实际偏移量是+11:00