Convert DateTime to Date, but TimeZone is missing?
By:Roy.LiuLast updated:2019-08-17
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!
From:一号门
COMMENTS