As others have said, it’s a problematic question in that a LocalTime
and a Date
really represent quite different and almost unrelated concepts. A LocalTime
is a time of day without time zone, such as 19:45 (or 7:45 PM). A Date
is a point on the time line; if it happens to coincide with 19:45 on some date in some time zone, it will not in other time zones.
I believe that the conventional way of misusing (indeed) a Date
for an hour of day is setting it to that time of day on January 1, 1970 in the default time zone of the JVM. This practice carries all of the liabilities already mentioned. In particular the JVM default time zone setting can be changed at any time from another part of your program or any other program running in the same JVM. This means that a completely unrelated program may suddenly cause your Date
to indicate a different time of day than the one you had initialized it to.
There’s nothing better we can do, so here goes:
LocalTime time = LocalTime.of(11, 0);
Instant timeOnEpochDayInDefaultTimeZone = LocalDate.EPOCH
.atTime(time)
.atZone(ZoneId.systemDefault())
.toInstant();
Date oldfashionedDateObject = Date.from(timeOnEpochDayInDefaultTimeZone);
System.out.println(oldfashionedDateObject);
In my time zone output from this snippet is:
Thu Jan 01 11:00:00 CET 1970
LocalTime
and aDate
really represent quite different and almost unrelated concepts. ALocalTime
is a time of day without time zone, such as 19:45 (or 7:45 PM). ADate
is a point on the time line; if it happens to coincide with 19:45 on some date in some time zone, it will not in other time zones. – Kerrikerrie