Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert LocalTime (Java 8) to Date

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.

like image 547
Jbartmann Avatar asked Oct 13 '15 09:10

Jbartmann


People also ask

What is a LocalTime in the Java 8 date and time API?

The LocalTime represents time without a date. Similar to LocalDate, we can create an instance of LocalTime from the system clock or by using parse and of methods.

What does LocalTime represent time without date?

What does LocalTime represent? Explanation: LocalTime of joda library represents time without date. 9.

What is the default format of LocalTime in Java 8?

LocalTime LocalTime is an immutable class whose instance represents a time in the human readable format. It's default format is hh:mm:ss. zzz.


1 Answers

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.

like image 189
Dariusz Avatar answered Oct 25 '22 02:10

Dariusz