I get date as string from backend and now at first...
# getting-started
j
I get date as string from backend and now at first I need to convert it to date time and then to compare this date and current date difference in years, months, weeks, days, minutes and seconds. In JS I can do this easily with moment JS like this
Copy code
function extractTime(time) {
  return {
    seconds: moment().diff(time, 'seconds'),
    minutes: moment().diff(time, 'minutes'),
    hours: moment().diff(time, 'hours'),
    days: moment().diff(time, 'days'),
    weeks: moment().diff(time, 'weeks'),
    months: moment().diff(time, 'months'),
    years: moment().diff(time, 'years'),
  };
}
Is there something similar in Kotlin that I can achieve same result?
m
You can get the duration of time passed between two
Instants
as a
Duration
. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.time/-duration/ But that only goes up to days. Does not support weeks, months, or years becomes the time include in that varies. To do what you want you would probably need to convert to a
LocalDateTime
and then just subtract the different parts handling the overflow behavior. Also need to beware that multiple
LocalDateTime
in the same location could represent different
Instants
because of how time jumps around due to day light savings time.
m
Things like weeks, months and years are nonsensical when looking at a duration so at least that makes sense. But you can make something comparable in Kotlin pretty easily with your JS example:
Copy code
fun extractTime(time: LocalDateTime) = ChronoUnit
    .values()
    .dropLast(1) // 'FOREVER' isn't a valid difference
    .associateWith { time.until(LocalDateTime.now(), it) }
This results into a map that looks like this:
Copy code
{Nanos=939897175910792688, Micros=939897175913782, Millis=939897175913, Seconds=939897175, Minutes=15664952, Hours=261082, HalfDays=21756, Days=10878, Weeks=1554, Months=357, Years=29, Decades=2, Centuries=0, Millennia=0, Eras=0}
You can manually check the diffs just like you did in your JS example too
👀 1
although I would ofcourse not use
LocalDateTime.now()
every time for the different call, not even in the 'seconds' example since time elapses per operation, but you get the gist
p
you could of course use
fun extractTime(time: LocalDateTime, since: LocalDateTime = LocalDateTime.now()) = …
to handle both cases neatly - allowing for a consistent delta for all chronounits and you can pass in a specific time for
since
when mapping over multiple dates
👀 1
i
With kotlinx.datetime you can express two moments as
Instant
values and then use
Instant.periodUntil(Instant, TimeZone)
returning
DateTimePeriod
type which provides components of period from years to nanoseconds.
👀 1