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

前端 未结 3 1855
星月不相逢
星月不相逢 2020-12-18 06:14

just to verify this: I have this lame and brain dead method to calculate the time zone offset for my current location. I wonder if I need to adjust it when Day Light Saving

相关标签:
3条回答
  • 2020-12-18 06:38

    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.
    0 讨论(0)
  • 2020-12-18 06:38

    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.

    0 讨论(0)
  • 2020-12-18 06:57

    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

    0 讨论(0)
提交回复
热议问题