Home > Enterprise >  Kotlin - Get difference between datetimes in seconds
Kotlin - Get difference between datetimes in seconds

Time:07-28

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

CodePudding user response:

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()

CodePudding user response:

If your date types are in the java.time package, in other words, are inheritors of Temporal: Use the ChronoUnit class.

val diffSeconds = ChronoUnit.SECONDS.between(date1, date2)

Note that this can result in a negative value, so do take its absolute value (abs) if necessary.

  • Related