2012-04-23 187 views
1

是否有一些內置的方法來檢查DateTimeZoneDateTime多少小時?Joda時間夏令時檢測

我寫了一個小工具類,但更喜歡內置方法。

public class Dst { 
    public static long dayHours(DateTime instant) { 
     Period day = new Period(0, 0, 0, 1, 0, 0, 0, 0); 
     return new Duration(instant, instant.plus(day)).getStandardHours(); 
    } 
    public static boolean hasClockChange(DateTime instant) { 
     return 24l != Dst.dayHours(instant); 
    } 
} 

回答

3

我不認爲有在JodaTime庫直接的方式,但也許有些短:

public static long dayHours(DateTime instant) { 
    return new Duration(instant.withMillisOfDay(0), 
         instant.withMillisOfDay(0).plus(Days.ONE)) 
         .getStandardHours(); 
} 

這是你貼什麼略有不同勢,因爲它看起來在這一天代表在提供的日期(丟棄時間)而不是在下一個 23/24/25小時,您實際上做了什麼,根據instant中包含的時間是在時間更改之前還是之後,這將會有所不同。

我問自己的問題是,你真的需要小時數嗎?或者只是當天是否有變化?然後使用這樣的事情:

public static boolean hasClockChange(DateTime instant) { 
     zone = DateTimeZone.forID("your-time-zone") // or do this with an appropriate constant 
     return zone.getOffset(instant.withMillisOfDay(0)) != zone.getOffset(instant.withHourOfDay(23)); 
} 

(假設時間變化不會發生在晚上11點後,這應該沒問題)。 如果您需要這些信息,您也可以根據時間變化的方向返回-1/0/1。