Search code examples
javajsonzoneddatetime

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?


Solution

  • Well let me break down the problem statement.

    First if you are querying an API then it can be assumed that they are following some standard Date-Time format (even if you are creating one). Looking over the given date it looks like they follow - ** ISO 8601 - Date and time format **

    So the problem is how to parse ISO 8601 - Date and time format

    What are best options available ?

    • Using Joda Time.
    • Using Date Time API Java-8

      //Joda
      String jtDate = "2010-01-01T12:00:00+01:00";
      DateTimeFormatter yoda = ISODateTimeFormat.dateTimeNoMillis();
      System.out.println(parser2.parseDateTime(jtDate));
      
      //using Java 8 (As you specified - To convert "+0100" to "+01:00"    is easy enough.)
      String strDate = "2017-01-05T16:32:29+01:00";
      DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
      TemporalAccessor convertMe = timeFormatter.parse(strDate);
      Date date = Date.from(Instant.from(convertMe));
      System.out.println(date);
      

    Hope it helps :)