Joda time's DateTime converted to java.util.Date strange issue

让人想犯罪 __ 提交于 2019-12-10 12:38:03

问题


I ran into a strange issue. Here is a snippet of code that describes it:

DateTimeZone dtz = DateTimeZone.forOffsetHours(0);

DateTime dt = new DateTime(dtz);

System.out.println(dt);
System.out.println(dt.toDate());

the output is:

2012-02-29T17:24:39.055Z
Wed Feb 29 19:24:39 EET 2012

I'm located UTC+2, but this action is supposed to create a java.util.Date object which is initialized for UTC time. What am I missing?


回答1:


Date doesn't know about a time zone at all - it only represents an instant in time (like Joda Time's Instant type). It's just a number of milliseconds since the Unix epoch. When you call Date.toString(), it always uses the system local time zone for converting that into a readable text form.

So there's nothing wrong here - just an expectations failure over either the meaning of java.util.Date or its toString() behaviour, or both.

(As an aside, prefer DateTimeZone.UTC over creating your own.)




回答2:


To get a JDK Date that matches Joda's DateTimeconvert to LocalDateTimefirst.

As explained in the other answers, the time in milliseconds does not change depending on the timezone:

DateTime local = DateTime.now()
Date localJDK = local.toDate()
assert localJDK.getTime() == local.toInstant().getMillis()

DateTime differentTimeZone = DateTime.now(DateTimeZone.forID('America/Chicago'))
Date localJDK2 = differentTimeZone.toDate()
assert differentTimeZone.toInstant().getMillis() == localJDK2.getTime()
assert localJDK.getTime() == localJDK2.getTime()

Converting a LocalDateTime to Date will change that:

Date differentTimeZoneJDK = differentTimeZone.toLocalDateTime().toDate()
assert localJDK.getTime() != differentTimeZoneJDK.getTime()



回答3:


The behaviour you want is this:

Date jdkDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dt.toString("yyyy-MM-dd HH:mm:ss"));

Like Jon noted, JDK date is time zone agnostic. Hope this helps someone.



来源:https://stackoverflow.com/questions/9503771/joda-times-datetime-converted-to-java-util-date-strange-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!