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

Can this be done? If so, how do I convert from Joda-Time to Date and vice versa?

+54
java datetime jodatime
Mar 11 '13 at 7:30
source share
3 answers

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(); 
+82
Mar 11 '13 at 7:33
source share

You did not specify what type in Joda time you are interested in, but:

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

Neither Date nor Instant is associated with time zones, so there is no need to specify here.

It makes no sense to convert from LocalDateTime / LocalDate / LocalTime to Date (or vice versa), as this will depend on the time zone used.

With DateTime you can convert to Date without specifying a time zone, but to convert from Date to DateTime you must specify the time zone or use the system’s default time zone. (If you really want this, I would directly point it out so that it is clear that this is a deliberate choice.)

For example:

 DateTimeZone zone = DateTimeZone.forID("Europe/London"); Date date = ...; DateTime dateTime = new DateTime(date.getTime(), zone); 
+6
Mar 11 '13 at 7:36 on
source share

Convert from Java Date to Joda Time:
To convert from Date to DateTime, you must specify the time zone.
To convert from java.util Date to Joda Time of Date, you just need to pass the java.util date and time zone for the Joda Time of Date constructor.

 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); 

Convert from Joda Date Time to Java Date:
For the opposite case, Joda DateTime has a toDate() method that will return the date java.util.

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

Read more ... Visit here

0
Mar 11 '13 at 7:36 on
source share



All Articles