LocalDateTime 的长时间戳

问题描述 投票:0回答:7

我有一个很长的时间戳 1499070300 (相当于 Mon, 03 Jul 2017 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());
java java-8 timestamp java-time
7个回答
169
投票

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

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

System.out.println(triggerTime);

结果:

2017-07-03T10:25

或使用

ofEpochSecond
代替:

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

System.out.println(triggerTime);

结果:

2017-07-03T10:25

9
投票

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

LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault())

6
投票

尝试以下..

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

如果末尾不包含 l,则默认

1499070300000
为 int。同时以毫秒为单位传递时间。


3
投票

您的问题是时间戳不是以毫秒为单位,而是以纪元日期开始的秒数表示。将时间戳乘以 1000 或使用

Instant.ofEpochSecond()


3
投票

尝试使用

Instant.ofEpochMilli()
Instant.ofEpochSecond()
方法 -

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

0
投票

简单直接的解决方案将(KOTLIN)

            val timeStamp:Long=559585985988
            val sdf = SimpleDateFormat("hh:mm:ss a - MMM dd,yyyy", Locale.getDefault())
            val tz = TimeZone.getDefault()
            val now = Date()
            val offsetFromUtc = tz.getOffset(now.time)
            val localeTimeStr = sdf.format(timeStamp + offsetFromUtc) //add the offset to get the local time from the epoch timestamp

0
投票

从 JDK 8 开始,还可以利用 EpochSeconds 的 LocalDateTime 方法:

private LocalDateTime epochSecondsToLocalDate(long epochSeconds) {
    ZoneId zoneId = ZoneOffset.systemDefault();
    ZoneOffset zoneOff = zoneId.getRules().getOffset(LocalDateTime.now());
    return LocalDateTime.ofEpochSecond(epochSeconds, 0, zoneOff);
}

或者,如果处理毫秒:

private LocalDateTime epochMillisToLocalDateTime(long epochMillis) {
    ZoneId zoneId = ZoneOffset.systemDefault();
    ZoneOffset zoneOff = zoneId.getRules().getOffset(LocalDateTime.now());
    return LocalDateTime.ofEpochSecond(epochMillis / 1000,
            (int) (epochMillis % 1000) * 1000000, zoneOff);
}

此方法首先将纪元时间戳除以 1000,将毫秒转换为秒,因为 LocalDateTime.ofEpochSecond 需要秒。余数 (epochMillis % 1000) 表示毫秒部分,然后将其转换为纳秒(乘以 1000000)作为 LocalDateTime.ofEpochSecond 的纳秒参数。

© www.soinside.com 2019 - 2024. All rights reserved.