如何在Joda Time中检测出模糊的DST重叠?

时间:2013-09-13 19:02:18

标签: java timezone jodatime dst

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文档很清楚如果在转换过程中存在重叠,除非另有说明,否则将采用更早的可能性。但它没有说明如何检测这种行为。

1 个答案:

答案 0 :(得分:10)

利用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)); 
}