skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search