Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 449
Time Avatar asked Mar 11 '13 07:03

Time


People also ask

What is the replacement of Joda-time?

time (JSR-310) which is a core part of the JDK which replaces joda library project.

Is Joda-time format followed in Java 8?

Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.

How do I import Joda-time?

Copy (or) drag & drop the joda-time-2.1. jar into the newly created libs folder. Right click on your project again (in package explorer) then Properties -> Java Build Path -> Libraries -> Add Jars -> joda-time-2.1. jar .

Is Joda-time deprecated?

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


2 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(); 
like image 126
Rahul Avatar answered Oct 22 '22 14:10

Rahul


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); 
like image 27
Jon Skeet Avatar answered Oct 22 '22 13:10

Jon Skeet