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
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 typeLocalDate
How am I supposed to do this correctly?
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
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.
Slightly different approach to what Zabuzard posted due to not using an Instant explicitly…
You will need to
String,-06:00 to UTC and thenString representation by means of a DateTimeFormatterSo… 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With