Joda 时间 两个日期之间的时间间隔(包括时区)

2024-03-22

我使用 JodaTime 库进行时间操作。 我有两个日期: 日期一:

DateTime time_server = new DateTime(server_time_milisecs).
    withZone(DateTimeZone.forID("Europe/Zurich"));  //+0100

Shows: 2013-01-27 13:44:42

日期二:

DateTime time_local = new DateTime(DateTime.now()).
    withZone(DateTimeZone.getDefault());    //Have "Europe/Moscow" timezone  +0400

Shows: 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 https://stackoverflow.com/questions/2653567/joda-whats-the-difference-between-period-interval-and-duration?rq=1)如果您需要进行涉及不同时区的时间计算。

例如,考虑以下代码

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(零)。正如它应该。

Because nowHere and nowZur代表同一个时刻(以实际线路时间为准),如两个不同的国家/地区所示。它们仅在表示方式上有所不同,但从物理上讲它们是相同的时间点(例如2.54 cm and 1 in长度相同,以两种不同的形式表示)。

同样地,2013-01-27T10:19:24.460-03:00 and 2013-01-27T14:19:24.460+01:00是同一时刻,即我运行该代码的时刻,仅根据不同国家/地区的惯例表示;火星人可以用他自己的火星历来代表同一时刻,而且它仍然是同一个瞬间.

由于这些 DateTime 代表相同的时间点,因此它们之间的物理间隔(持续时间)必须为零。现在,如果你想得到两者之间的“民用时差”,那是完全不同的事情。这LocalDateTimePeriod(完全不同于DateTime and Duration)将是正确的概念。例如:

Period per=new Period(nowHere.toLocalDateTime(),nowZur.toLocalDateTime());
System.out.println(per.toStandardSeconds().getSeconds());

这为我打印了 14400(4 个“标准”-非物理-小时)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Joda 时间 两个日期之间的时间间隔(包括时区) 的相关文章

随机推荐