org.joda.time | Day Light Saving time (DST) and local time zone offset

十年热恋 提交于 2019-11-29 07:28:26

Normally, Joda time will take care of DST by itself, so you don't have to worry about it. However, I notice that you are passing null to getOffset(). Given that the time zone offset depends on the date, you really should be passing the date/time at which you are calculating the offset, or you're going to get wrong results.

Also as mentionned in my previous comment: Be aware that some timezones have an offset that isn't a whole number of hours. India for example is at GMT +5:30

Basil Bourque

Time zones and Daylight Saving Time are a nightmare. You certainly shouldn't take on this task yourself. Let Joda-Time do the heavy lifting.

See this answer to similar question, Using Joda time to get UTC offset for a given date and timezone. The class DateTimeZone offers a getOffset() method.

Example source code in Joda-Time 2.3 in Java 7…

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

org.joda.time.DateTimeZone californiaTimeZone = org.joda.time.DateTimeZone.forID("America/Los_Angeles");

org.joda.time.DateTime now = new org.joda.time.DateTime(californiaTimeZone);
int millisecondOffsetToAddToUtcToGetLocalTime = californiaTimeZone.getOffset( now );

System.out.println( "millisecondOffsetToAddToUtcToGetLocalTime: " + millisecondOffsetToAddToUtcToGetLocalTime );

// Note the casting to doubles to avoid integer truncation. Time zone offsets are NOT always whole hours.
System.out.println( "Offset in decimal hours: " + (double)millisecondOffsetToAddToUtcToGetLocalTime / 1000d / 60d / 60d );

When run at 2013-11-20T01:03:56.464-08:00…

millisecondOffsetToAddToUtcToGetLocalTime: -28800000
millisecondOffsetToAddToUtcToGetLocalTime in hours: -8.0

IMPORTANT That number format -8.0 is incorrect for an offset. Must be either:

  • -08:00 with the colon and double digits (padded with leading zero).
  • -08 with leading zero.

Yes, that's fine. To verify that it is correct - instead of passing null pass in a DateTime object to DateTimeZone.getOffset - set the datetime to sometime in summer when you know DST is in effect - you should see the offset value change.

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