【问题标题】:How to detect an ambiguous DST overlap in Joda Time?如何在 Joda Time 中检测模糊的 DST 重叠?
【发布时间】:2013-09-18 13:26:44
【问题描述】:

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

【问题讨论】:

    标签: java timezone jodatime dst


    【解决方案1】:

    利用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-11-28
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      • 2016-01-16
      • 2020-11-13
      • 2015-05-22
      • 1970-01-01
      相关资源
      最近更新 更多