繁体   English   中英

如何计算两个“日期时间”之间的“持续时间”

[英]How to calculate 'Duration' between two 'DateTimes'

我有两个DateTime对象:

import org.joda.time.{DateTime, Hours}
import scala.concurrent.duration._

val t1: DateTime = DateTime.now
val t2: DateTime = /* Some other time in the future */

我想计算两者之间的持续时间:

val d: Duration = Duration(t2 - t1)

显然上面的代码不起作用。 我试过minus ,但这需要一个Duration ,而不是一个DateTime

什么是最简单的方法来做到这一点?

乔达时间

使用org.joda.time.Duration一对DateTime对象的org.joda.time.Duration构造函数。

Duration d = new Duration( t1 , t2 ) ;

时间

java.time.Duration类上使用静态工厂方法。

Duration d = Duration.between( t1 , t2 ) ;

同意@stefanobaghino,请尝试使用自 java 8 以来开箱即用的 java.time。关于您的情况,请检查以下内容

 Duration

public Duration(ReadableInstant start,
                ReadableInstant end)

    Creates a duration from the given interval endpoints.

    Parameters:
        start - interval start, null means now
        end - interval end, null means now 
    Throws:
        ArithmeticException - if the duration exceeds a 64 bit long

你离得很近,哈哈

import scala.concurrent.duration._

val d = Duration(t2.getMillis - t1.getMillis, MILLISECONDS)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM