How to convert Long local timestamp to String UTC timestamp

谁说胖子不能爱 提交于 2019-12-11 15:46:36

问题


This question is quite close to mine, However I find the answer not suitable for me. I have timestamp as Long.

ts = 1362156863140L

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

or

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"));

which returns:

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

another timezone:

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

returns:

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;

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?


回答1:


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);


来源:https://stackoverflow.com/questions/50584469/how-to-convert-long-local-timestamp-to-string-utc-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!