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().
Non-Java
I do not yet know Kotlin, but I can read the documentation.
The
LocalDateTimeclass 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
Instantclass 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
Instantobjects in theDateTimePeriodclass. No such class forLocalDateTime.So we should be able to assign a zero offset to turn our
LocalDateDateobjects intoInstantobjects. I do not know how to do this exactly, as I don't use Kotlin. But I imagine you can make aUtcOffsetby passing zero in all three arguments, then apply that to yourLocalDateTimeto wind your way to anInstant.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
Durationclass in the java.time classes.If your app will be deployed to a JVM, use java.time:
Duration.between( startLdt , endLdt ).