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

前端 未结 3 1857
星月不相逢
星月不相逢 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.

提交回复
热议问题