Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Joda LocalDate to java.util.Date?

What is the simplest way to convert a JodaTime LocalDate to java.util.Date object?

like image 250
Eric Wilson Avatar asked Apr 08 '11 15:04

Eric Wilson


People also ask

How do I get Util date from LocalDate?

Convert LocalDate To Date in Java Step 1: First Create the LocalDate object using either now() or of() method. now() method gets the current date where as of() creates the LocalDate object with the given year, month and day. Step 2: Next, Get the timezone from operating system using ZoneId. systemDefault() method.

Is Joda datetime deprecated?

So the short answer to your question is: YES (deprecated).

What is difference between LocalDate and date?

LocalDate is the date the calendar on the wall says. java. util. Date is not a date, it's an instant, and actually represents a millisecond offset from Unix epoch.


2 Answers

JodaTime

To convert JodaTime's org.joda.time.LocalDate to java.util.Date, do

Date date = localDate.toDateTimeAtStartOfDay().toDate();

To convert JodaTime's org.joda.time.LocalDateTime to java.util.Date, do

Date date = localDateTime.toDate();

JavaTime

To convert Java8's java.time.LocalDate to java.util.Date, do

Date date = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());

To convert Java8's java.time.LocalDateTime to java.util.Date, do

Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

You might be tempted to shorten it with LocalDateTime#toInstant(ZoneOffset), but there isn't a direct API to obtain the system default zone offset.

To convert Java8's java.time.ZonedDateTime to java.util.Date, do

Date date = Date.from(zonedDateTime.toInstant());
like image 126
BalusC Avatar answered Oct 23 '22 22:10

BalusC


Since 2.0 version LocalDate has a toDate() method

Date date = localDate.toDate();

If using version 1.5 - 2.0 use:

Date date = localDate.toDateTimeAtStartOfDay().toDate();

On older versions you are left with:

Date date = localDate.toDateMidnight().toDate();
like image 10
maraswrona Avatar answered Oct 23 '22 21:10

maraswrona