Home > Net >  How to convert date string in EDT to UTC date?
How to convert date string in EDT to UTC date?

Time:11-15

I am reading data from upstream system and it returns the date in string format like this,

String dateFromUpstream = 11-14-2022 10:41:12 EDT

Now, I want to convert this string to a date format of UTC timezone and then store it into my entity.

I tried the following way,

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss z");
LocalDateTime date = ZonedDateTime.parse(dateFromUpstream, formatter).toLocalDateTime().atZone(ZoneId.of("UTC"));

But this doesn't change the date to UTC timezone. It still gives me the same date with UTC instead of EDT at the end of the string.

Anyone know how I can do this and then store into an entity?

CodePudding user response:

Parse the given date-time string into a ZonedDateTime with the corresponding DateTimeFormatter and then convert the resulting ZonedDateTime into an Instant or another ZonedDateTime corresponding to UTC, using ZonedDateTime#withZoneSameInstant.

Demo:

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String dateFromUpstream = "11-14-2022 10:41:12 EDT";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-uuuu HH:mm:ss z", Locale.ENGLISH);
        ZonedDateTime zdt = ZonedDateTime.parse(dateFromUpstream, dtf);
        Instant instant = zdt.toInstant();
        System.out.println(instant);

        // Or get a ZonedDateTime at UTC
        ZonedDateTime zdtUTC = zdt.withZoneSameInstant(ZoneOffset.UTC);
        System.out.println(zdtUTC);

        // If you want LocalDateTime
        LocalDateTime ldt = zdtUTC.toLocalDateTime();
        System.out.println(ldt);
    }
}

See this code run at Ideone.com.

Output:

2022-11-14T15:41:12Z
2022-11-14T15:41:12Z
2022-11-14T15:41:12

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


Note: As suggested by Basil Bourque, you can convert the parsed date-time into an OffsetDateTime at UTC as shown below:

OffsetDateTime odtUTC = zdt.toOffsetDateTime()
                           .withOffsetSameInstant(ZoneOffset.UTC);
  •  Tags:  
  • java
  • Related