Search code examples
javascaladatetime-formatzoneddatetime

How to calculate the time difference in seconds?


I have two Datetime strings:

val formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd-hh-mm-ss")
val startTime = formatter format ZonedDateTime.now(ZoneId.of("UTC"))
//...
val endTime = formatter format ZonedDateTime.now(ZoneId.of("UTC"))

How can I calculate the difference in seconds between endTime and startTime?


Solution

  • Use a java.time.temporal.ChronoUnit:

    // difference in seconds
    ChronoUnit.SECONDS.between(startTime, endTime)
    

    But startTime and endTime must be ZonedDateTime objects, not Strings.

    Just keep in mind that the result is floor-rounded - if the real difference is, let's say, 1999 milliseconds, the code above will return 1 (because 1999 milliseconds are not enough to make 2 seconds).

    Another detail is that you can use ZoneOffset.UTC instead of ZoneId.of("UTC"), as the result is the same.

    Actually, if you're working with UTC, why not use Instant.now() instead? The between method above works the same way with Instant's:

    val start = Instant.now()
    val end = Instant.now()
    
    val diffInSecs = ChronoUnit.SECONDS.between(start, end)