Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 289
TAT Avatar asked Oct 30 '25 00:10

TAT


2 Answers

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.

like image 107
Zabuzard Avatar answered Nov 01 '25 13:11

Zabuzard


Slightly different approach to what Zabuzard posted due to not using an Instant explicitly…

You will need to

  • parse the String,
  • adjust the offset from -06:00 to UTC and then
  • get the desired String representation by means of a DateTimeFormatter

So… tl;dr:

public static void main(String[] args) {
    // example input
    String someDateTime = "2019-11-30T00:01:00.000-06:00";
    // parse directly
    OffsetDateTime odt = OffsetDateTime.parse(someDateTime);
    // define a DateTimeFormatter for the desired output
    DateTimeFormatter dtf = DateTimeFormatter
                                .ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX");
    // print the parsing result using the DateTimeFormatter
    System.out.println("Origin: " 
            + odt.format(dtf));
    // adjust the offset from -06:00 to UTC
    OffsetDateTime utcOdt = odt.withOffsetSameInstant(ZoneOffset.UTC);
    // print the result — again using the DateTimeFormatter
    System.out.println("UTC:    " 
            + utcOdt.format(dtf));
}

Output:

Origin: 2019-11-30T00:01:00.000-06:00
UTC:    2019-11-30T06:01:00.000Z
like image 32
deHaar Avatar answered Nov 01 '25 13:11

deHaar



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!