A-Sharabiani
A-Sharabiani

Reputation: 19329

How to calculate 'Duration' between two 'DateTimes'

I have two DateTime objects:

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

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

I want to calculate the duration between the two:

val d: Duration = Duration(t2 - t1)

Obviously the code above does not work. I tried minus, but that requires a Duration, not a DateTime.

What is the easiest way to do this?

Upvotes: 2

Views: 1419

Answers (3)

A-Sharabiani
A-Sharabiani

Reputation: 19329

import scala.concurrent.duration._

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

Upvotes: 0

Basil Bourque
Basil Bourque

Reputation: 338171

Joda-Time

Use org.joda.time.Duration constructor taking a pair of DateTime objects.

Duration d = new Duration( t1 , t2 ) ;

java.time

Use the static factory method on the java.time.Duration class.

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

Upvotes: 3

slesh
slesh

Reputation: 2007

Agree with @stefanobaghino, try to use java.time which is available out of box since java 8. Regarding your case, check 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

You was very close, hah

Upvotes: 0

Related Questions