我使用JodaTime库进行时间操作.我有两个日期:第一天:
DateTime time_server = new DateTime(server_time_milisecs).
withZone(DateTimeZone.forID("Europe/Zurich")); //+0100
Run Code Online (Sandbox Code Playgroud)
显示: 2013-01-27 13:44:42
第二天:
DateTime time_local = new DateTime(DateTime.now()).
withZone(DateTimeZone.getDefault()); //Have "Europe/Moscow" timezone +0400
Run Code Online (Sandbox Code Playgroud)
显示: 2013-01-27 16:41:47
我需要找到包括时区在内的实际间隔
Interval interval = new Interval(time_local, time_server);
Long.toString(interval.toDurationMillis()));
Run Code Online (Sandbox Code Playgroud)
结果:174040毫秒 - 不正确
int secs = Seconds.secondsBetween(time_local,time_server).getSeconds();
Run Code Online (Sandbox Code Playgroud)
结果:174秒不正确
Period period = new Period(time_local, time_server);
Integer.toString(period.getSeconds()) //**Wrong too**
Run Code Online (Sandbox Code Playgroud)
结果必须是:10974秒
leo*_*loy 27
如果你需要进行涉及不同时区的时间计算,你应该花一些时间(没有双关语)来掌握Jodatime概念(例如).
例如,请考虑以下代码
DateTime nowHere = DateTime.now();
DateTime nowZur = nowHere.withZone(DateTimeZone.forID("Europe/Zurich"));
System.out.println("now Here: " + nowHere );
System.out.println("now Zurich: " + nowZur );
Run Code Online (Sandbox Code Playgroud)
这输出(对我来说,偏离苏黎世4小时):
now Here: 2013-01-27T10:19:24.460-03:00
now Zurich: 2013-01-27T14:19:24.460+01:00
Run Code Online (Sandbox Code Playgroud)
暂停并尝试猜测以下行的输出:
Interval interv = new Interval(nowHere, nowZur);
System.out.println("Interval: " + interv.toDurationMillis());
Run Code Online (Sandbox Code Playgroud)
以上打印0(零).正如它应该.
因为nowHere并nowZur代表同一时刻(在物理线时间内),如两个不同国家所代表的那样.它们的区别仅在于它们的表示方式,但在物理上它们是相同的时间点(类似2.54 cm且1 in长度相同,以两种不同的形式表示).
同样,2013-01-27T10:19:24.460-03:00和2013-01-27T14:19:24.460+01:00是同一时刻,我在其中运行代码的那一刻,只有根据不同国家的惯例来表示; 火星人可以用他自己的火星日历代表同一瞬间,它仍然是同一时刻.
由于这些DateTime表示相同的时间点,因此它们之间的物理间隔(持续时间)必须为零.现在,如果你想获得两者之间的"民间时差",那就完全不同了.然后LocalDateTime,Period(完全不同于DateTime和Duration)将成为正确的概念.例如:
Period per=new Period(nowHere.toLocalDateTime(),nowZur.toLocalDateTime());
System.out.println(per.toStandardSeconds().getSeconds());
Run Code Online (Sandbox Code Playgroud)
这为我打印14400(4"标准" - 不是物理 - 小时)
| 归档时间: |
|
| 查看次数: |
19205 次 |
| 最近记录: |