Kotlin – Get difference between datetimes in seconds

Issue

Is there any way, to get the difference between two datetimes in seconds?

For example
First datetime: 2022-04-25 12:09:10
Second datetime: 2022-05-24 02:46:21

Solution

There is a dedicated class for that – Duration (the same in Android doc).

A time-based amount of time, such as ‘34.5 seconds’.
This class models a quantity or amount of time in terms of seconds and nanoseconds. It can be accessed using other duration-based units, such as minutes and hours. In addition, the DAYS unit can be used and is treated as exactly equal to 24 hours, thus ignoring daylight savings effects. See Period for the date-based equivalent to this class.

Here is example usage:

        val date1 = LocalDateTime.now()
        val date2 = LocalDateTime.now()

        val duration = Duration.between(date1, date2)

        val asSeconds: Long = duration.toSeconds()
        val asMinutes: Long = duration.toMinutes()

Answered By – Mateusz

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published