How to convert Joda-Time DateTime to java.util.Date and vice versa?

JavaDatetimeJodatimejava.util.date

Java Problem Overview


Is it possible to do that? If yes, then how do I do the conversion from Joda-Time to Date and vice versa?

Java Solutions


Solution 1 - Java

To convert Java Date to Joda DateTime:-

Date date = new Date();
DateTime dateTime = new DateTime(date);

And vice versa:-

Date dateNew = dateTime.toDate();

With TimeZone, if required:-

DateTime dateTimeNew = new DateTime(date.getTime(), timeZone);
Date dateTimeZone = dateTime.toDateTimeAtStartOfDay(timeZone).toDate();

Solution 2 - Java

You haven't specified which type within Joda Time you're interested in, but:

Instant instant = ...;
Date date = instant.toDate();
instant = new Instant(date);
// Or...
instant = new Instant(date.getTime());

Neither Date nor Instant are related to time zones, so there's no need to specify one here.

It doesn't make sense to convert from LocalDateTime / LocalDate / LocalTime to Date (or vice versa) as that would depend on the time zone being applied.

With DateTime you can convert to a Date without specifying the time zone, but to convert from Date to DateTime you should specify the time zone, or it will use the system default time zone. (If you really want that, I'd specify it explicitly to make it clear that it's a deliberate choice.)

For example:

DateTimeZone zone = DateTimeZone.forID("Europe/London");
Date date = ...;
DateTime dateTime = new DateTime(date.getTime(), zone);

Solution 3 - Java

To Convert from Java Date to Joda Time of Date:
To convert from Date to DateTime time zone needed to be specified.
To convert from java.util Date to Joda Time of Date you just need to pass the java.util Date and time zone to the constructor of Joda Time of Date.

java.util.Date date = new java.util.Date(System.currentTimeMillis());
DateTimeZone dtz = DateTimeZone.getDefault();// Gets the default time zone.
DateTime dateTime = new DateTime(date.getTime(), dtz);

To Convert from Joda Time of Date to Java Date:
For the reverse case Joda DateTime has a method toDate() which will return the java.util Date.

DateTime jodaDate = new DateTime();
java.util.Date date = jodaDate.toDate();

For More Details http://joda-time.sourceforge.net/userguide.html">Visit Here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimeView Question on Stackoverflow
Solution 1 - JavaRahulView Answer on Stackoverflow
Solution 2 - JavaJon SkeetView Answer on Stackoverflow
Solution 3 - JavaShreyos AdikariView Answer on Stackoverflow