Converting Date and Time Values to Legacy Date – Date and Time
By Gigi Rosen / September 24, 2023 / No Comments / Compact Number Parsing, Formatting and Parsing Messages, Oracle Certifications
17.8 Converting Date and Time Values to Legacy Date
An object of the java.util.Date legacy class represents time, date, and time zone. The class provides the method from() to convert a java.time.Instant (p. 1049) to a Date. In order to convert dates and times created using the new Date and Time API, we need to go through an Instant to convert them to a Date object.
The java.time.ZonedDateTime class provides the toInstant() method to convert a ZonedDateTime object to an Instant, which is utilized by the zdtToDate() method of the ConvertToLegacyDate utility class in Example 17.10 at (1).
A java.time.LocalDateTime object lacks a time zone in order to convert it to a Date. The ldtToDate() method at (2) adds the system default time zone to create a Zoned-DateTime object which is then converted to an Instant.
A LocalDate object lacks time and a time zone in order to convert it to a Date. The ldToDate() method at (3) adds a fictive time (start of the day), and the resulting LocalDateTime object is added the system default time zone to create a ZonedDateTime object which is then converted to an Instant.
A LocalTime object lacks a date and a time zone in order to convert it to a Date. The ltToDate() method at (4) adds a fictive date (2021-1-1), and the resulting LocalDateTime object is added to the system default time zone to create a ZonedDateTime object which is then converted to an Instant.
For an example, see Example 18.8, p. 1143.
Example 17.10 Converting to Legacy Date
import java.time.*;
import java.util.Date;
public class ConvertToLegacyDate {
/** Convert a ZonedDateTime to Date. */
public static Date zdtToDate(ZonedDateTime zdt) { // (1)
return Date.from(zdt.toInstant());
}
/** Convert a LocalDateTime to Date. */
public static Date ldtToDate(LocalDateTime ldt) { // (2)
return Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
}
/** Convert a LocalDate to Date. */
public static Date ldToDate(LocalDate ld) { // (3)
return Date.from(ld.atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant());
}
/** Convert a LocalTime to Date. */
public static Date ltToDate(LocalTime lt) { // (4)
return Date.from(lt.atDate(LocalDate.of(2021, 1, 1))
.atZone(ZoneId.systemDefault())
.toInstant());
}
}