What's the best way to get the difference between ...
# kotlinx-datetime
a
What's the best way to get the difference between two date times (time in 24hr format)?
a
Could you provide an example of what you mean?
a
Yes. I've two dates:
date1 = "2024-05-17 22:05"
date2 = "2024-05-18 12:44"
I want the delta in milliseconds between
date2
and
date1
AND also for the cases where
date2
is before
date1
(e.g.
date2 = "2024-05-17 22:04"
)
a
There is no UTC offset specified for these datetimes. Is it guaranteed that they are from the same timezone? Also, can DST transitions happen?
a
Right. They're from the same timezone, and yes, DST transitions can happen. Should I convert to UTC and use that to calculate the difference?
a
Yep, first, convert these values to
Instant
, then, subtract them: https://kotlinlang.org/api/kotlinx-datetime/kotlinx-datetime/kotlinx.datetime/-instant/minus.html (the second overload in the list)
👍 1
s
Should I convert to UTC?
Converting to UTC will give you an answer, but it's not the only answer. DST means the duration between two otherwise identical
LocalDateTime
instances can be different depending on your location. If your dates and times correspond to real events in the real world, you need to use the actual timezone in which those events take place.
a
Is there a library where, when supplied with a city (e.g. Dublin,Ohio,USA or Dublin,Ireland) to be returned the timezone of that location?
s
You'd need a big database of place names to do that properly. I've used https://www.geonames.org/ in the past. They have a web API and you can also download all the data for free.
Normally when dealing with users, it's easier just to get the user to tell you their timezone. Or look up the timezone that their browser/device is using.
a
Mmmm, yeah. I wanted to make it easier for them, not to have to translate into other timezones from their own, but rather be assured that they can use a timezone based on a location and that the time in that timezone will respect said timezone. I guess, I'll just leave it for later as it is cumbersome. A nice feature. 🙂
s
There are many time zone IDs based on city names, so you can write "America/New_York" instead of "EST" and Kotlin will understand it. That might be a good compromise. It's a finite list, though—you wouldn't be able to do "America/Dublin".
a
What about other cities in the vicinity of NY? Will they automatically get translated to "America/New_York"?
s
Kotlin only knows the ones it knows, which on JVM is currently a fixed list of about 600 time zone IDs. If you type in anything else that doesn't exactly match one of the known IDs, it'll just fail. It won't guess. That's where you'd need an actual database of place names.
👍 1
👍🏻 1