首页 > 解决方案 > 如何将长本地时间戳转换为字符串 UTC 时间戳

问题描述

这个问题很接近我的,但是我发现答案不适合我。我的时间戳很长。

ts = 1362156863140L

因为它很长,我认为它是时区天真的时间戳,对吗?这是科隆当地时间的时间戳 - UTC+0200 (CET)。因此,当我将其转换为字符串时区感知时间戳时,我想获得:

2013-03-01T14:54:23.140Z

或者

2013-03-01T16:54:23.140+02:00

我在问题开始时使用答案中的解决方案:

Instant.ofEpochMilli(timestamp).atOffset(ZoneOffset.of("+2"));

返回:

2013-03-01T18:54:23.140+02:00

另一个时区:

Instant.ofEpochMilli(timestamp).atOffset(ZoneOffset.of("Z"));

返回:

2013-03-01T16:54:23.140Z

所以这些方法并没有真正改变时区,它们只是改变了时间戳的表示。我还尝试了另一种方法:

OffsetDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.of("UTC"));

但结果完全一样。这个解决方案很有用,但原始方法:

int offset = TimeZone.getTimeZone("Europe/Amsterdam").getRawOffset();
long newTime = timestamp - offset;

不考虑夏季/冬季时间。建议的答案使用 JDK8 已过时的 Calendar 类。有效且足够明显的是:

OffsetDateTime.ofInstant(Instant.ofEpochMilli(Timestamp), ZoneId.of("UTC")).minusSeconds(7200);

但这显然不是正确的方法,那么我该如何使用时区来做到这一点?

标签: javajava-8timezonetimestamp

解决方案


我想时间戳在UTC,您需要将时间戳更改为CET. 看看withZoneSameInstant()方法,可能会有帮助。

    long timeStamp = 1362156863140L;
    ZoneId sourceZone = ZoneId.of("UTC");
    ZoneId targetZone = ZoneId.of("CET");
    String s = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timeStamp), sourceZone)
            .withZoneSameLocal(targetZone)
            .toString();
    System.out.println(s);

推荐阅读