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();
tl;dr
No need for
LocalDateTime,ZoneId,ZonedDateTimeclasses.Details
You said:
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.No need for the time zone. Both
java.util.Dateandjava.time.Instantrepresent 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.And the other direction:
Beware of data loss in this other direction. An
Instanthas a resolution of nanoseconds, whilejava.util.Dateresolves to milliseconds.