-2

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?

Markus
  • 3,562
  • 12
  • 48
  • 85

1 Answers1

2

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)
adedde
  • 36
  • 2
  • Do you mean this? `val start = Instant.now()`, `val end = Instant.now()`, `Instant.between(start,end)` – Markus Feb 20 '18 at 12:40
  • @Markus `ChronoUnit.SECONDS.between(start, end)` – adedde Feb 20 '18 at 12:40
  • How can I get Unix timestamp from `ZonedDateTime.now(ZoneId.of("UTC"))` or `Instant.now()` using `getEpochSecond()`? – Markus Feb 20 '18 at 12:45
  • @Markus `getEpochSecond()` return just the seconds value. To get the timestamp in milliseconds, use `Instant.now().toEpochMilli()` - or `ZonedDateTime.now(ZoneOffset.UTC).toInstant().toEpochMilli()` – adedde Feb 20 '18 at 12:48
  • Could you please upvote my question? – Markus Feb 20 '18 at 13:05