2013-03-18 69 views
3

正如我打字时那样,我自己想出了它。我将回答我自己的问题,包括我自己在内的未来用户。jodatime本地数据时间间隔

我希望能够在一段时间内保存到LocalDateTime对象,但似乎不允许。当我这样做:

LocalDateTime start = new LocalDateTime(); 

    LocalDateTime end = start.plusMinutes(30); 

    Interval interval = new Interval(start, end); 

我得到编译问题。我认为这是因为LocalDateTime不是ReadableInstant

有没有合适的解决方法?

看起来这是可能的:

周期期间=新周期(开始,结束);

但是,你失去了“getStart \ End”方法。

回答

4

为了使用IntervalLocalDateTime你必须这样做:

Interval interval = new Interval(start.toDateTime(), end.toDateTime()); 

产生的时间可以很容易地调试的时间会从本地时区转换,你知道是什么时候带你正在处理。但是在夏令时期间它会有问题。要解决此问题,请将结果强制为DateTimeZone.UTC,在这种情况下,您将丢失与时间相关的时区数据(如果您实际上始于LocalDateTime,则通常不关心这些数据,但请确保始终如一地使用它并永不建立您的Interval •不用转换。

Interval interval = new Interval( 
    start.toDateTime(DateTimeZone.UTC), end.toDateTime(DateTimeZone.UTC)); 

这是通过下面的试验证明了(假设你在EST时区)

@Test 
public void testLocalDateTimeDST() { 
    LocalDateTime dst_2017_03_12 = LocalDateTime.parse("2017-03-12T02:01:00"); 
    System.out.println(dst_2017_03_12); 
    try { 
     System.out.println(dst_2017_03_12.toDateTime()); 
     Assert.fail("Should've thrown an IllegalInstantException"); 
    } catch (IllegalInstantException e) { 

    } 
    System.out.println(dst_2017_03_12.toDateTime(DateTimeZone.UTC)); 
} 
+3

方法'toDateTime()'的LocalDateTime对象使用转换为DateTime **默认区域**,因此,通过这样做,您将违背LocalDateTime的目标用途表示没有时区的日期时间。如果你写的东西适合你,那么你应该从一开始就使用DateTime对象。 – mradzinski 2015-07-08 15:00:09

+0

LocalDateTime在许多业务场景中实际上很有用,因为许多业务应用程序不处理24x7配置,而是处理当地时间。他们通常在当地工作时间与人打交道。 – 2017-02-20 16:23:28