How to create a java.util.Date with absolute values for fields without timezone offset changing the values?

情到浓时终转凉″ 提交于 2019-12-12 01:05:22

问题


I'm trying to create a date with absolute values for the fields through JODA DateTime, for example (the example is in the epoch for easier examples):

new DateTime(1970, 1, 1, 1, 0, 0, 0, DateTimeZone.forId("GMT+0").toDate()

The JODA DateTime object correctly represents the hour as 1AM, if I inspect it all the absolute values are precise and correct (1 hour, 3600 seconds, 3600000 millis since the epoch, etc.) but as soon as toDate() and java.util.Date kicks in it becomes 2AM because he's adding the DST of my system's current time, even though I explicitly created the DateTime object with GMT+0 offset.

How can I ignore DST offset and just tell Java to create me a java.util.Date with the absolute values I want? Unfortunately I'm dealing with legacy code and I'm stuck with using java.util.Date so switching everything to Joda is not an option in the short term.

Thanks.


回答1:


java.util.Date does not store any time zone or DST-offset itself because it just stores the elapsed milliseconds since UNIX epoch, not counting leap seconds.

What you observe is rather the output of the toString()-method of j.u.Date which indeed is dependent on your local (JVM) time zone! So you have no error, only that j.u.Date has confusing behaviour.

Added: If you want to have a "correct" display of your Date-object then you need a format tool like SimpleDateFormat which you can use for any formatted output you wish.



来源:https://stackoverflow.com/questions/21604194/how-to-create-a-java-util-date-with-absolute-values-for-fields-without-timezone

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