2012-04-23 188 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。