Java 8 – How to Convert LocalTime to Date

datejavajava-8java-time

I'm trying to convert a java.time.LocalTime object to java.util.Date but can't find any suitable method. What's the correct way to do this?

Is there any reason why java doesn't seem to ship with a built-in direct conversion method?

To possible duplicates:
How to convert joda time – Doesn't work for me, probably I'm missing some "joda" libraries?
How to convert Date to LocalTime? – This adresses conversion the other way around.

Best Answer

LocalTime actually can't be converted to a Date, because it only contains the time part of DateTime. Like 11:00. But no day is known. You have to supply it manually:

LocalTime lt = ...;
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
        atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);

Here's a blog post which explains all the conversions between the new and the old API.

There's no simple built-in conversion method, because these APIs approach the idea of date and time in completely different way.