Calculate the time difference

Viewed 335

I am trying to calculate time difference between 2 ZonedTime dates in Scala. I am receiving dates in "2021-03-19T15:39:42.834248-07:00" format as a String. I need the difference in seconds between 2 dates in Scala. How to convert the string to zoned time and calculate the difference?

2 Answers

You'll want to use the between() method as offered on a temporal.ChronoUnit.

import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit.SECONDS

val start = ZonedDateTime.parse("2021-03-19T15:39:42.834248-07:00")
val stop  = ZonedDateTime.parse("2021-03-19T15:49:42.834248-08:00")
val secsBetween:Long = SECONDS.between(start, stop)  // 4200

An alternative is to use the until() method on the ZonedDateTime instance itself.

val secsBetween:Long = start.until(stop, SECONDS) //same result

[Java syntax, not Scala.]

tl;dr

Duration
.between
(
    OffsetDateTime.parse( "2021-03-19T15:39:42.834248-07:00" ) ,
    OffsetDateTime.parse( "2021-03-19T15:49:42.834248-08:00" )
)
.toString()

See this code run live at IdeOne.com.

PT1H10M

…which in standard ISO 8601 format means 1 hour and 10 minutes.

Details

The Answer by jwvh is close, but I would change a couple things.

OffsetDateTime, not ZonedDateTime

Your input strings have only a mere offset-from-UTC but no time zone. So parse those as OffsetDateTime.

  • An offset is simply a number of hours-minutes-seconds ahead or behind the baseline of UTC, the line drawn through Royal Observatory, Greenwich. An example of an offset is -07:00 which means seven hours behind UTC.
  • A time zone is much more. A time zone is history of the past, present, and future changes to the offset used by the people of a particular region. A time zone has a name in format of Continent/Region. Given our example above, on some dates, several time zones may share the offset of -07:00, including America/Dawson, America/Los_Angeles, America/Phoenix, America/Boise, and more.
OffsetDateTime odt = OffsetDateTime.parse( "2021-03-19T15:39:42.834248-07:00" ) ;

Duration

Represent a span-of-time using Duration, on the scale of hours-minutes-seconds-nanos.

Duration d = Duration.between( sooner , later ) ;

Generate text in standard ISO 8601 format.

String output = d.toString() ;
Related