如何将长本地时间戳转换为字符串UTC时间戳 [英] How to convert Long local timestamp to String UTC timestamp
问题描述
这个问题非常接近我,但我发现答案不适合我。我有时间戳为长。
This question is quite close to mine, However I find the answer not suitable for me. I have timestamp as Long.
ts = 1362156863140L
因为它很长我认为它是时区天真的时间戳,是吗?这是科隆当地时间的时间戳 - UTC + 0200(CET)。因此,当我将其转换为字符串时区感知时间戳时,我想获得:
As it is Long I consider it as timezone naive timestamp, is that right? It is timestapm in local time in Cologne - UTC+0200 (CET). So when I convert it to String timezone aware timestamp I want to obtain:
2013-03-01T14:54:23.140Z
或
2013-03-01T16:54:23.140+02:00
我正在使用解决方案从我的问题开头的答案:
I'm using solution from answer in the beginning of my question:
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
所以这些方法并不是真的更改时区,它们只是更改时间戳的表示。我还尝试了另一种方法:
So those methods does not really change the timezone, they just change representation of timestamp. I also tried another method:
OffsetDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.of("UTC"));
但结果完全相同。 此解决方案很有用,但原创方法:
But results are exactly the same. This solutions was useful, but original approach:
int offset = TimeZone.getTimeZone("Europe/Amsterdam").getRawOffset();
long newTime = timestamp - offset;
夏季/冬季时间不统一。建议的答案使用Calendar类,这对JDK8来说已经过时了。有效且显而易见的是:
does not concider summer/winter time. And suggested answers use Calendar class, which is obsolete for JDK8. What works and is obvious enough is:
OffsetDateTime.ofInstant(Instant.ofEpochMilli(Timestamp), ZoneId.of("UTC")).minusSeconds(7200);
但这不是一个正确的方法,所以我怎么能用时区做到这一点?
But it is defenetly not a proper way to do this, so how can I do that with timezone?
推荐答案
我想时间戳是 UTC
,你需要改变时间戳到 CET
。看看 withZoneSameInstant()
方法,可能会有所帮助。
I suppose that timestamp is in UTC
and you need to change timestamp to CET
. Take a look at withZoneSameInstant()
method, might be helpful.
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);
这篇关于如何将长本地时间戳转换为字符串UTC时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!