Как рассчитать «Длительность» между двумя «Дата и время» - PullRequest
2 голосов
/ 17 марта 2020

У меня есть два 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.

Какой самый простой способ сделать это?

Ответы [ 3 ]

3 голосов
/ 18 марта 2020

Joda-Time

Использовать org.joda.time.Duration конструктор, принимающий пару DateTime объектов.

Duration d = new Duration( t1 , t2 ) ;

java .time

Используйте фабричный метод stati c для класса java.time.Duration.

Duration d = Duration.between( t1 , t2 ) ;
0 голосов
/ 23 марта 2020
import scala.concurrent.duration._

val d = Duration(t2.getMillis - t1.getMillis, MILLISECONDS)
0 голосов
/ 17 марта 2020

Согласитесь с @stefanobaghino, попробуйте использовать java .time, который доступен «из коробки» с java 8. Что касается вашего случая, отметьте this :

 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

Ты был очень близко, ха

...