javautcjava-timejava.time.instantoffsetdatetime

Convert timestamp with offset to UTC


Conversion

I have a timestamp with an offset (-6) in the following format:

2019-11-30T00:01:00.000-06:00

and I want to convert it to an UTC timestamp, like:

2019-11-30T06:01:00.000Z

Attempt

I tried it the following way:

String text = "2019-11-30T00:01:00.000-06:00";

LocalDate date = LocalDate.parse(text, DateTimeFormatter.BASIC_ISO_DATE);

System.out.println(date.toInstant());

but it is not compiling:

The method toInstant() is undefined for the type LocalDate

How am I supposed to do this correctly?


Solution

  • tl;dr

    String text = "2019-11-30T00:01:00.000-06:00";
    OffsetDateTime offsetDateTime = OffsetDateTime.parse(text);
    Instant instant = offsetDateTime.toInstant();
    
    System.out.println(instant); // 2019-11-30T06:01:00Z
    
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
      .withZone(ZoneOffset.UTC);
    System.out.println(formatter.format(instant)); // 2019-11-30T06:01:00.000Z
    

    Explanation

    Your date is not just a date, it also has time. So LocalDate would not work. If at all, then LocalDateTime.

    But, it is also not a local date/time, it has offset information. You need to use OffsetDateTime instead, and then go to Instant from there.

    To actually get the desired output for your Instant, you also have to create a proper DateTimeFormatter, since the default representation does not include the millis.