0

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?

2 Answers2

2

** 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"));
Jamie Bisotti
  • 2,605
  • 19
  • 23
  • Thanks, it worked :) The output converted to string in this case would be "2022-12-22T23:20Z[UTC]". Using @AndreyB.Panfilov 's answer we can get a string without the timezone "2022-12-22T23:20:00Z". – Lingua Franca Dec 15 '22 at 06:38
  • 3
    Good Answer, but I would make that second line an `OffsetDateTime` as there is no time zone, only an offset. – Basil Bourque Dec 15 '22 at 06:39
1

The accepted answer is correct but there are a few things that are important for future visitors to this page.

You do not need to specify a DateTimeFormatter

java.time API is based on ISO 8601 and therefore you do not need to specify a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format (e.g. your date-time string, 2015-03-21T11:08:14.859831).

Get an Instant out of the ZonedDateTime

Once you convert the LocalDateTime, parsed from the given date-time string, into a ZonedDateTime, I recommend you get an Instant out of this ZonedDateTime. An Instant is an instantaneous point on the timeline, and normally this is represented using a UTC timescale.

US/Eastern is deprecated

As you find at List of tz database time zones, US/Eastern is deprecated. I recommend you avoid using US/Eastern and use America/New_York instead.

Demo:

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;

class Main {
    public static void main(String[] args) {
        ZoneId zone = ZoneId.of("America/New_York");

        ZonedDateTime zdt = LocalDateTime.parse("2022-12-22T18:20:00.000")
                                         .atZone(zone);
        // Alternatively
        // zdt = ZonedDateTime.of(LocalDateTime.parse("2022-12-22T18:20:00.000"), zone);

        Instant instant = zdt.toInstant();
        System.out.println(instant);
    }
}

Output:

2022-12-22T23:20:00Z

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110