Convert DateTime to Date, but TimeZone is missing?

A code snippet to use Joda Time to convert a java.util.Date to different timezone :


//java.util.Date : 22-1-2015 10:15:55 AM
//System TimeZone : Asia/Singapore

//Convert java.util.Date to America/New_York TimeZone
DateTime dt = new DateTime(date);
DateTimeZone dtZone = DateTimeZone.forID("America/New_York");
DateTime dtus = dt.withZone(dtZone); //21-1-2015 09:15:55 PM - Correct!

//Convert Joda DateTime back to java.util.Date, and print it out
Date dateInUS = dtus.toDate();
System.out.println(dateInUS); //22-1-2015 10:15:55 AM - What???Why???

The problem is, if you convert back the Joda DateTime to java.util.Date, the timezone will revert back to system default TimeZone!?

Solution

In Java, java.util.Date doesn’t know about timezone, If a java.util.Date is printed with toString(), it will always print the date with system default TimeZone.

To fix it, convert DateTime to Joda LocalDateTime first.


DateTime dt = new DateTime(date);
DateTimeZone dtZone = DateTimeZone.forID("America/New_York");
DateTime dtus = dt.withZone(dtZone); //21-1-2015 09:15:55 PM - Correct!

Date dateInUS = dtus.toLocalDateTime().toDate();
System.out.println(dateInUS); //21-1-2015 09:15:55 PM - Correct!

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Abhay Kumar
Guest
Abhay Kumar
Hi Mkyong, Date dateInUS = dtus.toLocalDateTime().toDate(); The above line converts the datetime to date , but it changes the time zone on which the server is running. If i run on my local (i.e in India) then the time shown is 21-1-2015 09:15:55 PM IST which ideally should be 21-1-2015 09:15:55 PM America/New_York i.e the time comes according to America/new york but it appends IST. Similarly if i run it on server where time zone is UTC , then it changes to 21-1-2015 09:15:55 PM UTC (i.e the time zone specified in the server) which ideally should be 21-1-2015 09:15:55… Read more »
Balaji Ganesan
Guest
Balaji Ganesan

We are also facing the same issue. It appears using the toLocalDateTime is causing this issue. Using just the toDate seems fine.

Vishal Joshi
Guest
Vishal Joshi

Converting to ‘toLocalDateTime()’ does not solve the problem as it sticks the server time zone with the changed date. This lets the date to give out wrong information.

Kisna
Guest
Kisna

But why can’t JodaTime also set the timezone information correctly on java.util.Date? Both dates have a timezone equal to System TimeZone : Asia/Singapore “which is wrong at least for display purposes” isn’t it?