Lukas Lechner
Lukas Lechner

Reputation: 8181

What's the best way to convert LocalDate and LocalTime to java.util.date?

I have a org.threeten.bp.LocalDate and a org.threeten.bp.LocalTime and I do need a java.util.date instance. Whats the best way to archieve this. I looked through DateTimeUtils but found no proper solution.

Upvotes: 4

Views: 5378

Answers (2)

Meno Hochschild
Meno Hochschild

Reputation: 44061

Here is the better solution without using deprecated stuff but using the helper class DateTimeUtils:

// your input (example)
LocalDate date = LocalDate.of(2015, 4, 3);
LocalTime time = LocalTime.of(17, 45);

// the conversion based on your system timezone
Instant instant = date.atTime(time).atZone(ZoneId.systemDefault()).toInstant();
Date d = DateTimeUtils.toDate(instant);
System.out.println(d); // Fri Apr 03 17:45:00 CEST 2015

You need a timezone to make this conversion working. I have chosen the system timezone in the example given above but you are free to adjust the timezone to your needs.

Upvotes: 5

Lukas Lechner
Lukas Lechner

Reputation: 8181

Life can be so easy:

Date date = Date(localDate.year,localDate.monthValue,localDate.dayOfMonth,localTime.hour,localTime.minute, localTime.second)

edit: oh wait.... this is deprecated! So another solution would be better!

Upvotes: -2

Related Questions