kotlindatetimedate-differencekotlinx-datetime

Kotlin difference between two LocalDateTime


I have two kotlinx.datetime.LocalDateTime instances:

val startDate =
LocalDateTime(year = 2020, month = Month.MARCH, dayOfMonth = 25, hour = 10, minute = 
36, second = 12)
val endDate =
LocalDateTime(year = 2023, month = Month.FEBRUARY, dayOfMonth = 28, hour = 0, minute 
= 0, second = 1)

I want to compute difference between these two dates but I don't want to use Java way. how can I achive this ? by the way I'm doing micro optimization so I can't convert those to Instant to use Instant.until().


Solution

  • Non-Java

    I do not yet know Kotlin, but I can read the documentation.

    The LocalDateTime class represents a date with time-of-day, but lacks the context of a time zone or offset-from-UTC. So this class cannot represent a moment, a point on the timeline.

    In contrast, the Instant class does represent a moment, a point on the timeline. This class represent a date with time-of-day as seen with an offset of zero hours-minutes-seconds from UTC.

    You can get the amount of time elapsed between two Instant objects in the DateTimePeriod class. No such class for LocalDateTime.

    So we should be able to assign a zero offset to turn our LocalDateDate objects into Instant objects. I do not know how to do this exactly, as I don't use Kotlin. But I imagine you can make a UtcOffset by passing zero in all three arguments, then apply that to your LocalDateTime to wind your way to an Instant.

    In your Question, you were reluctant to go this route because of "micro optimization". I have no idea what you meant. But that route is the one I would choose. Otherwise, you will need write your own implementation to calculated elapsed time.

    Java

    kotlinx-datetime is a library that imitates the java.time framework bundled with Java, but contains only a limited subset of the functionality. This library is for Kotlin apps that will not be deployed to a JVM.

    In your case, the missing piece you need is the Duration class in the java.time classes.

    If your app will be deployed to a JVM, use java.time: Duration.between( startLdt , endLdt ).

    Duration d = 
        Duration.between( 
            LocalDateTime.of ( 2020, Month.MARCH, 25, 10, 36, 12 ) ,
            LocalDateTime.of ( 2023, Month.FEBRUARY, 28, 0, 0, 1 )
        ) ;