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

末鹿安然 提交于 2019-12-02 05:15:10

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

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