[java] How to convert ZonedDateTime to Date?

I am trying to set a server agnostic date time in my database and I believe the best practice to do so is to set a UTC DateTime. My db server is Cassandra and the db driver for Java understands only the Date type.

So assuming that in my code I am using the new Java 8 ZonedDateTime to get the UTC now (ZonedDateTime.now(ZoneOffset.UTC)), how can I convert this ZonedDateTime instance to the "legacy" Date class?

The answer is


You can do this using the java.time classes built into Java 8 and later.

ZonedDateTime temporal = ...
long epochSecond = temporal.getLong(INSTANT_SECONDS);
int nanoOfSecond = temporal.get(NANO_OF_SECOND);
Date date = new Date(epochSecond * 1000 + nanoOfSecond / 1000000);

The accepted answer did not work for me. The Date returned is always the local Date and not the Date for the original Time Zone. I live in UTC+2.

//This did not work for me
Date.from(java.time.ZonedDateTime.now().toInstant()); 

I have come up with two alternative ways to get the correct Date from a ZonedDateTime.

Say you have this ZonedDateTime for Hawaii

LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneId.of("US/Hawaii"); // UTC-10

or for UTC as asked originally

Instant zulu = Instant.now(); // GMT, UTC+0
ZonedDateTime zdt = zulu.atZone(ZoneId.of("UTC"));

Alternative 1

We can use java.sql.Timestamp. It is simple but it will probably also make a dent in your programming integrity

Date date1 = Timestamp.valueOf(zdt.toLocalDateTime());

Alternative 2

We create the Date from millis (answered here earlier). Note that local ZoneOffset is a must.

ZoneOffset localOffset = ZoneOffset.systemDefault().getRules().getOffset(LocalDateTime.now());
long zonedMillis = 1000L * zdt.toLocalDateTime().toEpochSecond(localOffset) + zdt.toLocalDateTime().getNano() / 1000000L;
Date date2 = new Date(zonedMillis);

I use this.

public class TimeTools {

    public static Date getTaipeiNowDate() {
        Instant now = Instant.now();
        ZoneId zoneId = ZoneId.of("Asia/Taipei");
        ZonedDateTime dateAndTimeInTai = ZonedDateTime.ofInstant(now, zoneId);
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateAndTimeInTai.toString().substring(0, 19).replace("T", " "));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

Because Date.from(java.time.ZonedDateTime.ofInstant(now, zoneId).toInstant()); It's not work!!! If u run your application in your computer, it's not problem. But if you run in any region of AWS or Docker or GCP, it will generate problem. Because computer is not your timezone on Cloud. You should set your correctly timezone in Code. For example, Asia/Taipei. Then it will correct in AWS or Docker or GCP.

public class App {
    public static void main(String[] args) {
        Instant now = Instant.now();
        ZoneId zoneId = ZoneId.of("Australia/Sydney");
        ZonedDateTime dateAndTimeInLA = ZonedDateTime.ofInstant(now, zoneId);
        try {
            Date ans = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateAndTimeInLA.toString().substring(0, 19).replace("T", " "));
            System.out.println("ans="+ans);
        } catch (ParseException e) {
        }
        Date wrongAns = Date.from(java.time.ZonedDateTime.ofInstant(now, zoneId).toInstant());
        System.out.println("wrongAns="+wrongAns);
    }
}

tl;dr

java.util.Date.from(  // Transfer the moment in UTC, truncating any microseconds or nanoseconds to milliseconds.
    Instant.now() ;   // Capture current moment in UTC, with resolution as fine as nanoseconds.
)

Though there was no point in that code above. Both java.util.Date and Instant represent a moment in UTC, always in UTC. Code above has same effect as:

new java.util.Date()  // Capture current moment in UTC.

No benefit here to using ZonedDateTime. If you already have a ZonedDateTime, adjust to UTC by extracting a Instant.

java.util.Date.from(             // Truncates any micros/nanos.
    myZonedDateTime.toInstant()  // Adjust to UTC. Same moment, same point on the timeline, different wall-clock time.
)

Other Answer Correct

The Answer by ssoltanid correctly addresses your specific question, how to convert a new-school java.time object (ZonedDateTime) to an old-school java.util.Date object. Extract the Instant from the ZonedDateTime and pass to java.util.Date.from().

Data Loss

Note that you will suffer data loss, as Instant tracks nanoseconds since epoch while java.util.Date tracks milliseconds since epoch.

diagram comparing resolutions of millisecond, microsecond, and nanosecond

Your Question and comments raise other issues.

Keep Servers In UTC

Your servers should have their host OS set to UTC as a best practice generally. The JVM picks up on this host OS setting as its default time zone, in the Java implementations that I'm aware of.

Specify Time Zone

But you should never rely on the JVM’s current default time zone. Rather than pick up the host setting, a flag passed when launching a JVM can set another time zone. Even worse: Any code in any thread of any app at any moment can make a call to java.util.TimeZone::setDefault to change that default at runtime!

Cassandra Timestamp Type

Any decent database and driver should automatically handle adjusting a passed date-time to UTC for storage. I do not use Cassandra, but it does seem to have some rudimentary support for date-time. The documentation says its Timestamp type is a count of milliseconds from the same epoch (first moment of 1970 in UTC).

ISO 8601

Furthermore, Cassandra accepts string inputs in the ISO 8601 standard formats. Fortunately, java.time uses ISO 8601 formats as its defaults for parsing/generating strings. The Instant class’ toString implementation will do nicely.

Precision: Millisecond vs Nanosecord

But first we need to reduce the nanosecond precision of ZonedDateTime to milliseconds. One way is to create a fresh Instant using milliseconds. Fortunately, java.time has some handy methods for converting to and from milliseconds.

Example Code

Here is some example code in Java 8 Update 60.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
…
Instant instant = zdt.toInstant();
Instant instantTruncatedToMilliseconds = Instant.ofEpochMilli( instant.toEpochMilli() );
String fodderForCassandra = instantTruncatedToMilliseconds.toString();  // Example: 2015-08-18T06:36:40.321Z

Or according to this Cassandra Java driver doc, you can pass a java.util.Date instance (not to be confused with java.sqlDate). So you could make a j.u.Date from that instantTruncatedToMilliseconds in the code above.

java.util.Date dateForCassandra = java.util.Date.from( instantTruncatedToMilliseconds );

If doing this often, you could make a one-liner.

java.util.Date dateForCassandra = java.util.Date.from( zdt.toInstant() );

But it would be neater to create a little utility method.

static public java.util.Date toJavaUtilDateFromZonedDateTime ( ZonedDateTime zdt ) {
    Instant instant = zdt.toInstant();
    // Data-loss, going from nanosecond resolution to milliseconds.
    java.util.Date utilDate = java.util.Date.from( instant ) ;
    return utilDate;
}

Notice the difference in all this code than in the Question. The Question’s code was trying to adjust the time zone of the ZonedDateTime instance to UTC. But that is not necessary. Conceptually:

ZonedDateTime = Instant + ZoneId

We just extract the Instant part, which is already in UTC (basically in UTC, read the class doc for precise details).


Table of date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


If you are using the ThreeTen backport for Android and can't use the newer Date.from(Instant instant) (which requires minimum of API 26) you can use:

ZonedDateTime zdt = ZonedDateTime.now();
Date date = new Date(zdt.toInstant().toEpochMilli());

or:

Date date = DateTimeUtils.toDate(zdt.toInstant());

Please also read the advice in Basil Bourque's answer


If you are interested in now only, then simply use:

Date d = new Date();

Here is an example converting current system time to UTC. It involves formatting ZonedDateTime as a String and then the String object will be parsed into a date object using java.text DateFormat.

    ZonedDateTime zdt = ZonedDateTime.now(ZoneOffset.UTC);
    final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss");
    final DateFormat FORMATTER_YYYYMMDD_HH_MM_SS = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
    String dateStr = zdt.format(DATETIME_FORMATTER);

    Date utcDate = null;
    try {
        utcDate = FORMATTER_YYYYMMDD_HH_MM_SS.parse(dateStr);
    }catch (ParseException ex){
        ex.printStackTrace();
    }

For a docker application like beehuang commented you should set your timezone.

Alternatively you can use withZoneSameLocal. For example:

2014-07-01T00:00+02:00[GMT+02:00] is converted by

Date.from(zonedDateTime.withZoneSameLocal(ZoneId.systemDefault()).toInstant())

to Tue Jul 01 00:00:00 CEST 2014 and by

Date.from(zonedDateTime.toInstant())

to Mon Jun 30 22:00:00 UTC 2014


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to java-8

Default interface methods are only supported starting with Android N Class has been compiled by a more recent version of the Java Environment Why is ZoneOffset.UTC != ZoneId.of("UTC")? Modify property value of the objects in list using Java 8 streams How to use if-else logic in Java 8 stream forEach Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit What are functional interfaces used for in Java 8? java.time.format.DateTimeParseException: Text could not be parsed at index 21 Java 8 lambda get and remove element from list

Examples related to java.util.date

How to convert ZonedDateTime to Date? Get the current date in java.sql.Date format Convert java.util.date default format to Timestamp in Java How to subtract X day from a Date object in Java? How to add minutes to my Date Convert java.util.Date to String How to set time zone of a java.util.Date? Calculating the difference between two Java date instances

Examples related to datetime-conversion

How to convert ZonedDateTime to Date? How to check if DST (Daylight Saving Time) is in effect, and if so, the offset? Convert from days to milliseconds Compare DATETIME and DATE ignoring time portion

Examples related to zoneddatetime

How to convert ZonedDateTime to Date?