Java - convert unix time in miliseconds with time zone to timestamp

五迷三道 提交于 2019-12-02 10:23:51

问题


I have a string for example:

1517439600000+0100

and I want to convert it to unix time in miliseconds with no timezone. how can I do it?

p.s. 1) I cant use substring(0,5) and add 3.6m miliseconds to the string because I have a lot of time zone once is +0100 and then is +0200 and etc...

2) if it more easier to convert to regular timestamp like YYYY-mm-dd hh:mm:ss it should be fine.


回答1:


You can do something like:

    String sign = "+";
    String [] parts = time.split(sign);

    Long millis = Long.parseLong(parts[0]);
    String zoneOffset = sign + parts[1];

    LocalDate date = Instant.ofEpochMilli(millis).atZone(ZoneOffset.of(zoneOffset)).toLocalDate();



回答2:


    String exampleString = "1517439600000+0100";
    // Split string before + or-
    String[] parts = exampleString.split("(?=[+-])");
    if (parts.length != 2) {
        throw new IllegalArgumentException("Unexpected/unsupported format: " + exampleString);
    }
    // Parse the milliseconds into an Instant
    Instant timeStamp = Instant.ofEpochMilli(Long.parseLong(parts[0]));
    // Parse the offset into a ZoneOffset
    DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("xx");
    ZoneOffset offset = ZoneOffset.from(offsetFormatter.parse(parts[1]));
    // Combine
    OffsetDateTime dateTime = timeStamp.atOffset(offset);
    System.out.println(dateTime);

Output:

2018-02-01T00:00+01:00

The number of milliseconds since the epoch (1 517 439 600 000) denotes a point in time independently of time zone or offset. So for getting a timestamp it’s enough to parse this number. If you’re happy with the Instant (2018-01-31T23:00:00Z in the example), you can of course drop the last half of the code. My style would be to harvest all the information from the string also when I don’t need all of it right away.

The regular expression I use for splitting, (?=[+-]), is a positive look-ahead: it matches the empty string before a + or -. Matching the empty string is important so no part of the string gets lost in the splitting (we need to preserve the sign).

A simpler way to parse the offset is ZoneOffset.of(parts[1]) (as NiVeR does in another answer). The only difference is that the DateTimeFormatter I use also validates that the format is indeed either like +0100 (no colon) or Z.



来源:https://stackoverflow.com/questions/52531649/java-convert-unix-time-in-miliseconds-with-time-zone-to-timestamp

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