javadatetimedatetime-conversion

Given ISO and timezone strings, how to convert them to UTC string in Java?


For example, I have an ISO string "2022-12-22T18:20:00.000", and a timezone string "US/Eastern". How do I convert them into a UTC time in the same format (iso 8601), using Java?


Solution

  • ** Update **

    A better version, thanks to Arvind's response below.

        final ZonedDateTime americaNewYork =
                LocalDateTime.parse("2022-12-22T18:20:00.000")
                             .atZone(ZoneId.of("America/New_York"));
        final Instant utc = americaNewYork.toInstant();
    

    First Pass

    I'm not at a computer where I can test this but I think this might do the trick...

        final ZonedDateTime usEastern =
                LocalDateTime.parse("2022-12-22T18:20:00.000", DateTimeFormatter.ISO_DATE_TIME)
                             .atZone(ZoneId.of("US/Eastern"));
        final ZonedDateTime utc = usEastern.withZoneSameInstant(ZoneId.of("UTC"));