Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine TimeZone from a JSON String?

I'm querying a JSON API that returns something like this:

{
  "created_time": "2017-01-05T16:32:29+0100",
  "updated_time": "2017-01-11T09:38:41+0100",
  "id": "23842536731240607"
}

I need to store the times in UTC format, but in order to change the timezone, I first need to parse it as a ZonedDateTime.

To convert "+0100" to "+01:00" is easy enough. But how can I parse the (created/updated)_time into a ZonedDateTime so I can convert it to UTC?

like image 696
gtludwig Avatar asked Mar 14 '26 14:03

gtludwig


1 Answers

There are some options.

First, as you say, inserting a colon in zone offset is not that difficult. After you’ve done that, getting a ZonedDateTime is straightforward:

    ZonedDateTime zdt = ZonedDateTime.parse("2017-01-11T09:38:41+01:00");
    System.out.println(zdt);

This prints:

2017-01-11T09:38:41+01:00

Alternatively, funnily, while ZonedDateTime.parse(String) needs a colon in the offset, ZoneId.of() does not, so you may split off the offset and do:

    ZoneId zi = ZoneId.of("+0100");
    LocalDateTime ldt = LocalDateTime.parse("2017-01-11T09:38:41");
    ZonedDateTime zdt = ldt.atZone(zi);

The result is the same as before.

If you prefer not to modify your string prior to parsing it, there is also:

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
    ZonedDateTime zdt = ZonedDateTime.parse("2017-01-11T09:38:41+0100", dtf);

Also this gives the same result.

Edit: Note: I am using ZonedDateTime since you asked for this in your question. You may consider it more correct to use OffsetDateTime. Most of the code is practically the same. The version that splits off the offset would go like this:

    ZoneOffset zo = ZoneOffset.of("+0100");
    LocalDateTime ldt = LocalDateTime.parse("2017-01-11T09:38:41");
    OffsetDateTime odt = ldt.atOffset(zo);

To convert to UTC, as mentioned at end of Question, apply another ZoneOffset, the constant ZoneOffset.UTC.

OffsetDateTime odtUtc = odt.withOffsetSameInstant( ZoneOffset.UTC );
like image 133
Ole V.V. Avatar answered Mar 16 '26 02:03

Ole V.V.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!