【问题标题】:How to get the time difference between 2 dates in millisec using JodaTime如何使用 JodaTime 以毫秒为单位获取 2 个日期之间的时间差
【发布时间】:2015-04-22 22:08:29
【问题描述】:

我要设计一个应用程序,我需要在其中获取两个日期之间的确切时间差。例如:

Date1:31/05/2011 12:54:00
Date2:31/05/2011 13:54:00

我尝试使用getTime(),但没有得到确切的结果。

上述输入的预期输出是 3600000 (60 * 60 * 1000) 毫秒,但我得到的是 46800000 (13 * 60 * 60 * 1000)。

当我浏览不同的 Java 论坛时,人们建议使用 JodaTime。

我仍然无法得到确切的结果。

我工作的时区是伦敦 (GMT)。

【问题讨论】:

  • 如果您得到的是 13 小时的差异而不是 1 小时的差异:您在执行计算时是否检查过它不是上午 12 点还是下午 1 点?我首先想到的就是这些方面的东西。
  • 另外 - 你应该知道伦敦的时区不是GMT,而是Europe/London。两者看起来很相似,直到您遇到极端情况(例如夏令时),然后您想知道为什么所有时间都相差一小时。

标签: java jodatime


【解决方案1】:

初始化两个 dateTime 并使用 Period :

DateTime dt1 = new DateTime(2013,9,11,9,58,56);
DateTime dt2 = new DateTime(2013,9,11,9,58,59);
Period p = new Period(dt1, dt2, PeriodType.millis());

以毫秒为单位:

System.out.println(p.getValue(0));

【讨论】:

  • 使用p.getMillis()会比引用索引更好
  • joda-time 的 Period 类(从 joda-time 2.9.9 开始)仅支持毫秒字段中的 int 值,因此当两个日期(以毫秒为单位)之间的差异溢出整数存储时,此方法会中断.要看到它中断,请将 dt1 更改为 dt1 = new DateTime(1970, 1, 1, 0, 0, 0);
【解决方案2】:
public static long getDiff(Calender cal1, Calender cal2)
{
    return Math.abs(cal1.getTimeInMillis() - cal2.getTimeInMillis());
}

【讨论】:

  • 这可能是最有效的方法。为此 +1。
【解决方案3】:

查看secondsBetween( )

创建一个 Seconds 表示两个时间之间的整秒数 两个指定的部分日期时间。 两个部分必须包含相同的字段,例如您可以 指定两个 LocalTime 对象。

参数:

 start - the start partial date, must not be null
    end - the end partial date, must not be null 

返回:

 the period in seconds 

【讨论】:

    【解决方案4】:

    JodaTime 在内部使用机器时间。因此,要查找毫秒,您可以使用存储 LocalDateTime 的常量来表示 1970 年 1 月 1 日(因为 UNIX Time)。

    Unix 时间,或 POSIX 时间,是一种用于描述时间点的系统, 定义为自午夜前经过的秒数 1970 年 1 月 1 日的协调世界时 (UTC),不包括闰 秒。然后计算您的 DateTime 之间的差异。

    我试过这样;

    public static void main(String[] args) {
            final LocalDateTime JAN_1_1970 = new LocalDateTime(1970, 1, 1, 0, 0);
            DateTime local = new DateTime().withZone(DateTimeZone.forID("Europe/Amsterdam"));
            DateTime utc = new DateTime(DateTimeZone.UTC);
    
            System.out.println("Europe/Amsterdam milis :" + new Duration(JAN_1_1970.toDateTime(DateTimeZone.forID("Europe/Amsterdam")), local).getMillis());
            System.out.println("UTC  milis             :" + new Duration(JAN_1_1970.toDateTime(DateTimeZone.UTC), utc).getMillis());
    
        }
    

    结果是;

    Europe/Amsterdam milis :1429695646528
    UTC  milis             :1429692046534
    

    @leonbloyhere 一个很好的评论。

    您的 local 和 UTC 代表相同的时间瞬间,(仅 附加不同的时区)。因此,getMillis()(给出 从对应的“瞬间”经过的“物理”时间间隔 unix epoch),必须返回相同的值。

    【讨论】:

      【解决方案5】:

      Joda 是一个完美的库,但如果您需要以毫秒为单位的 2 个日期之间的差异,您只需计算 getTime() 之间的差异。如果你得到错误的结果,你会遇到一些时区问题。通常它会起作用。

      【讨论】:

      • “Joda 是一个完美的库”.... 看看new DateTime((Date)null) 的实现然后告诉我:)
      猜你喜欢
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      相关资源
      最近更新 更多