In order to convert from Date to Instant, the solution can rely on the Date.toInstant() method. The reverse can be accomplished via the Date.from(Instant instant) method:
- Date to Instant can be accomplished like this:
Date date = new Date();
// e.g., 2019-02-27T12:02:49.369Z, UTC
Instant instantFromDate = date.toInstant();
- Instant to Date can be accomplished like this:
Instant instant = Instant.now();
// Wed Feb 27 14:02:49 EET 2019, default system time zone
Date dateFromInstant = Date.from(instant);
Keep in mind that Date is not time-zone aware, but it is displayed in the system default time zone (for example, via toString()). Instant is with a UTC time zone.
Let's quickly wrap these snippets of code in two utility methods, defined in a utility class—DateConverters:
public static Instant dateToInstant(Date date) {
return date.toInstant();
}
public static Date instantToDate(Instant instant) {
return Date.from(instant);
}
Further, let's enrich this class with the methods from the following screenshot:
The constant from the screenshot, DEFAULT_TIME_ZONE, is the system default time zone:
public static final ZoneId DEFAULT_TIME_ZONE = ZoneId.systemDefault();