LocalDateTime的长时间戳

rha*_*dom 42 java timestamp java-8 java-time

我有一个很长的时间戳1499070300(相当于周一,2017年7月3日16:25:00 +0800)但是当我将它转换为LocalDateTime时,我得到1970-01-18T16:24:30.300

这是我的代码

long test_timestamp = 1499070300;

LocalDateTime triggerTime =
                LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp), TimeZone
                        .getDefault().toZoneId());
Run Code Online (Sandbox Code Playgroud)

Jua*_*uan 64

您需要以毫秒为单位传递时间戳:

long test_timestamp = 1499070300000L;
LocalDateTime triggerTime =
        LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp), 
                                TimeZone.getDefault().toZoneId());  

System.out.println(triggerTime);
Run Code Online (Sandbox Code Playgroud)

结果:

2017-07-03T10:25
Run Code Online (Sandbox Code Playgroud)

或者ofEpochSecond改为使用:

long test_timestamp = 1499070300L;
LocalDateTime triggerTime =
       LocalDateTime.ofInstant(Instant.ofEpochSecond(test_timestamp),
                               TimeZone.getDefault().toZoneId());   

System.out.println(triggerTime);
Run Code Online (Sandbox Code Playgroud)

结果:

2017-07-03T10:25
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,如果你使用AndroidThreeTen,用`DateTimeUtils.toZoneId(TimeZone.getDefault())`替换`TimeZone.getDefault().toZoneId()`. (5认同)

Jam*_*ieH 8

如果您使用的是 Android Threeten 后端口,那么您想要的行是这样的

LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault())
Run Code Online (Sandbox Code Playgroud)


Aks*_*hay 6

尝试以下..

long test_timestamp = 1499070300000L;
    LocalDateTime triggerTime =
            LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp), TimeZone
                    .getDefault().toZoneId());  
Run Code Online (Sandbox Code Playgroud)

1499070300000如果最后不包含 l,则默认为 int。也以毫秒为单位传递时间。