user1354825
user1354825

Reputation: 1521

Convert a String to ZonedDateTime in UTC

I have a String which contains date in ZonedDateTime - UTC format. Example :-

2020-08-21T02:05:45.231Z

I want to convert it to a variable of type ZonedDateTime. What should be the pattern on the formatter?

(Note the time ending in "Z" which indicates UTC)

Upvotes: 0

Views: 2800

Answers (2)

deHaar
deHaar

Reputation: 18558

Due to this example String being in ISO format with a valid time zone abbreviation, you can directly parse it without passing a pattern.

Just like this:

public static void main(String[] args) {
    ZonedDateTime zdt = ZonedDateTime.parse("2020-08-21T02:05:45.231Z");
    System.out.println(zdt);
}

The output is then (again) the ISO-formatted String

2020-08-21T02:05:45.231Z

Please note that an OffsetDateTime should be preferred here because UTC is not a real time zone, it is the Coordinated Universal Time, the time without an offset.
The code is just slightly different:

public static void main(String[] args) {
    OffsetDateTime odt = OffsetDateTime.parse("2020-08-21T02:05:45.231Z");
    System.out.println(odt);
}

with exactly the same output.

For the sake of completeness, this is how to parse your example String to an Instant:

public static void main(String[] args) {
    Instant instant = Instant.parse("2020-08-21T02:05:45.231Z");
    System.out.println(instant.toEpochMilli());
}

This time, the output is the very same moment in time represented by epoch milliseconds (milliseconds since 1970-01-01'T'00:00:00.000...):

1597975545231

Upvotes: 4

ntalbs
ntalbs

Reputation: 29438

You can also use DateTimeFormatter.ISO_ZONED_DATE_TIME.

jshell> DateTimeFormatter.ISO_ZONED_DATE_TIME.parse("2020-08-21T02:05:45.231Z")
=> {InstantSeconds=1597975545, OffsetSeconds=0},ISO resolved to 2020-08-21T02:05:45.231

Upvotes: 1

Related Questions