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)