9

Joda Time中,可以很容易地使用该DateTimeZone.isLocalDateTimeGap方法来判断本地日期和时间是否无效,因为它落入了由春季向前夏令时转换所造成的差距。

DateTimeZone zone = DateTimeZone.forID("America/New_York");
LocalDateTime ldt = new LocalDateTime(2013, 3, 10, 2, 0);
boolean inGap = zone.isLocalDateTimeGap(ldt);  // true

但是你如何检测回退转换呢?换句话说,如果本地日期和时间由于重叠而可能不明确,您如何检测到呢?我会期待类似的东西zone.isLocalDateTimeOverlap,但它不存在。如果是这样,我会像这样使用它:

DateTimeZone zone = DateTimeZone.forID("America/New_York");
LocalDateTime ldt = new LocalDateTime(2013, 11, 3, 1, 0);
boolean overlaps = zone.isLocalDateTimeOverlap(ldt);  // true

Joda-Time 文档清楚地表明,如果在转换过程中存在重叠,除非另有说明,否则它将采用较早的可能性。但它没有说明如何检测这种行为。

4

1 回答 1

11

利用withEarlierOffsetAtOverlap()

public static boolean isInOverlap(LocalDateTime ldt, DateTimeZone dtz) {
    DateTime dt1 = ldt.toDateTime(dtz).withEarlierOffsetAtOverlap();
    DateTime dt2 = dt1.withLaterOffsetAtOverlap();
    return dt1.getMillis() != dt2.getMillis();
}


public static void test() {
    // CET DST rolls back at 2011-10-30 2:59:59 (+02) to 2011-10-30 2:00:00 (+01)
    final DateTimeZone dtz = DateTimeZone.forID("CET");
    LocalDateTime ldt1 = new LocalDateTime(2011,10,30,1,50,0,0); // not in overlap
    LocalDateTime ldt2 = new LocalDateTime(2011,10,30,2,50,0,0); // in overlap
    System.out.println(ldt1 + " is in overlap? " + isInOverlap(ldt1, dtz)); 
    System.out.println(ldt2 + " is in overlap? " + isInOverlap(ldt2, dtz)); 
}
于 2013-09-13T20:07:15.580 回答