How do I convert a Java Date into an Instant for a given timezone?

5.9k Views Asked by At

I have an instance of the Date class and a time zone (e.g Europe/London). How do I convert this into an Instant? Is the below the correct way of doing this?

LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of(timeZone));
Instant instant = zonedDateTime.toInstant();
1

There are 1 best solutions below

0
Basil Bourque On

tl;dr

myJavaUtilDate.toInstant()

No need for LocalDateTime, ZoneId, ZonedDateTime classes.

Details

You said:

I have an instance of the Date class

java.util.Date myJavaUtilDate = … ;

This class is now legacy, years ago supplanted by the modern java.time classes defined in JSR 310. Specifically replaced by java.time.Instant, to represent a moment, a specific point on the timeline, as seen with an offset of zero hours-minutes-seconds from the temporal meridian of UTC.

and a time zone (e.g Europe/London)

ZoneId z = ZoneId.of( "Europe/London" ) ;

How do I convert this into an Instant?

No need for the time zone. Both java.util.Date and java.time.Instant represent a moment as seen in UTC, as described above.

New conversion methods were added to the old classes. Look for the naming conventions of to… & from…. You can convert back and forth between the legacy classes and the modern classes. Stick to the modern classes. Use the legacy date-time classes only to interoperate with old code not yet updated to java.time.

java.time.Instant instant = myJavaUtilDate.toInstant() ;

And the other direction:

java.util.Date d = java.util.Date.from( instant ) ;

Beware of data loss in this other direction. An Instant has a resolution of nanoseconds, while java.util.Date resolves to milliseconds.