How to convert ZonedDateTime to Date?

Milen Kovachev picture Milen Kovachev · Aug 28, 2015 · Viewed 118.3k times · Source

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?

Answer

Slim Soltani Dridi picture Slim Soltani Dridi · Aug 28, 2015

You can convert ZonedDateTime to an instant, which you can use directly with Date.

Date.from(java.time.ZonedDateTime.now().toInstant());