Search code examples
datetimejava-8responsedifference

How to get the seconds difference between now() and TimeStamp with microseconds (2020-10-06T08:52:54.3556219Z) and using Java 8?


I wanted to calculate the difference between the current time and timestamp in microseconds (2020-10-06T08:52:54.3556219Z) that I received in the response using Java 8, please advise. I have used the following and I didn't get anything concrete solution, hence asking here!

  1. LocalDateTime
  2. ZonedDateTime
  3. SimpleDateFormat

Solution

  • You can use Instant and call .getEpochSecond() to get the seconds then calculate difference in second

    Instant dateTime = Instant.parse("2020-10-06T10:05:45.027416200Z");     
    Instant nowDateTime = Instant.now(); // 2020-10-06T10:44:23.173333200Z
    long diffSeconds = nowDateTime.getEpochSecond() - dateTime.getEpochSecond();
    

    Output: 2318