Search code examples
javadatejava-8timezone

Convert ZonedDateTime to java.util.Date


How do i convert ZonedDateTime to java.util.Date without changing the timezone.

In my below method when i call Date.from(datetime.toInstant()) it convert it to local time zone in my case SGT.

public static void printDate(ZonedDateTime datetime) {
    System.out.println("---> " + datetime.format(DateTimeFormatter.ofPattern(API_TIME_STAMP_PATTERN)));
    System.out.println(Date.from(datetime.toInstant()));
    System.out.println("\n");
}

Output

---> 2019-03-13_08:46:26.593
Wed Mar 13 16:46:26 SGT 2019

Solution

  • You can add offset millis by yourself. See the example using java.util.Date:

    long offsetMillis = ZoneOffset.from(dateTime).getTotalSeconds() * 1000;
    long isoMillis = dateTime.toInstant().toEpochMilli();
    Date date = new Date(isoMillis + offsetMillis);