我将JodaTime库用于时间操作。
我有两个约会:
日期一:
DateTime time_server = new DateTime(server_time_milisecs).
withZone(DateTimeZone.forID("Europe/Zurich")); //+0100
显示:
2013-01-27 13:44:42
日期二:
DateTime time_local = new DateTime(DateTime.now()).
withZone(DateTimeZone.getDefault()); //Have "Europe/Moscow" timezone +0400
显示:
2013-01-27 16:41:47
我需要找到包括时区的真实间隔
Interval interval = new Interval(time_local, time_server);
Long.toString(interval.toDurationMillis()));
结果:174040毫秒-不正确
int secs = Seconds.secondsBetween(time_local,time_server).getSeconds();
结果:174秒不正确
Period period = new Period(time_local, time_server);
Integer.toString(period.getSeconds()) //**Wrong too**
结果必须是:10974秒
最佳答案
如果需要进行涉及不同时区的时间计算,则应该花一些时间(不要双关语)来掌握Jodatime概念(eg)。
例如,考虑以下代码
DateTime nowHere = DateTime.now();
DateTime nowZur = nowHere.withZone(DateTimeZone.forID("Europe/Zurich"));
System.out.println("now Here: " + nowHere );
System.out.println("now Zurich: " + nowZur );
输出结果(对我来说,距离苏黎世有4个小时的偏移):
now Here: 2013-01-27T10:19:24.460-03:00
now Zurich: 2013-01-27T14:19:24.460+01:00
暂停并尝试猜测以下各行的输出:
Interval interv = new Interval(nowHere, nowZur);
System.out.println("Interval: " + interv.toDurationMillis());
上面显示
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());
这会为我打印14400(4个“标准”-非物理小时)
关于jodatime - 两个日期之间的Joda时间间隔,包括时区,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14547599/