【问题标题】:Comparing two Joda-Time DateTime objects比较两个 Joda-Time DateTime 对象
【发布时间】:2013-06-18 15:23:43
【问题描述】:

我正在处理的事情与这里所问的非常相似 - compare Joda-Time time zones 但它似乎对我不起作用。

这是我正在测试Joda-Time DateTime 的一段代码 -

 DateTime estDT = new DateTime(DateTimeZone.forID("America/Puerto_Rico")).withMillisOfSecond(0); 
 DateTime londonDT = new DateTime(DateTimeZone.forID("Europe/London")).withMillisOfSecond(0);

    System.out.println("Comparison " + londonDT.isBefore(estDT)); 
    System.out.println("Comparison " + londonDT.isAfter(estDT)); 

有趣的是,我从上面的两个 sysout 语句中都得到了“错误”。谁能解释一下进行这种比较的正确方法是什么?

【问题讨论】:

    标签: java jodatime


    【解决方案1】:

    isAfter 和 isBefore 方法按毫秒比较日期(忽略时区)。

    在您的示例中,日期的毫秒数相等。

    System.out.println(londonDT.getMillis() == estDT.getMillis());  
    

    将打印true。

    表达式

    londonDT.isBefore(estDT) 
    londonDT.isAfter(estDT)
    

    等于

    londonDT.getMillis() < estDT.getMillis()  
    londonDT.getMillis() > estDT.getMillis()
    

    【讨论】:

      【解决方案2】:

      您正在创建两个 DateTime 实例,它们可能代表同一时间点,但时区不同。两者都不是在另一个之前或之后。

      时区只会影响日期/时间方法(如getHourOfDay())如何转换瞬间。

      【讨论】:

      • 从技术上讲,londonDT 将 在 estDT 之后的时刻表示为宇宙时间线上的点。两行单独的代码意味着计算机时钟的两次单独采样,因此第二行发生的时间晚于第一行。 DateTime 的分辨率为毫秒,因此如果这两行代码恰好在计算机时钟的同一毫秒内执行,那么它们将彼此相等。这纯粹是运气(机会)。根据 Java 线程在执行期间是否延迟/暂停,或者如果它在较慢的计算机上运行,​​这两个 DateTime 可能不同。
      • 我们都太强了。鉴于对 withMillisOfSecond(0) 的调用,这两个 可能 代表同一时刻。但是,如果它们碰巧在不同的秒数上执行(例如,millis=999 和 millis=0),它们可能会有所不同。如果实际上需要同一时刻,则 withZone() 方法将比两次获取该时刻更可靠。但是,OP 更有可能需要两个不同的时间实例,作为输入提供。
      猜你喜欢
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 2018-08-30
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多