Jasmin Fajkic
07/20/2022, 7:20 PMfunction 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?mkrussel
07/20/2022, 7:31 PMInstants
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.Michael de Kaste
07/21/2022, 9:46 AMfun 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:
{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 tooMichael de Kaste
07/21/2022, 9:48 AMLocalDateTime.now()
every time for the different call, not even in the 'seconds' example since time elapses per operation, but you get the gistphldavies
07/21/2022, 9:56 AMfun 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 datesilya.gorbunov
07/21/2022, 4:54 PMInstant
values and then use Instant.periodUntil(Instant, TimeZone)
returning DateTimePeriod
type which provides components of period from years to nanoseconds.