Django's handling of datetimes in the admin interface can be greatly improved

You know the UTC offset for the server’s timezone right now, and the UTC for the user’s timezone right now. Using that difference to translate an arbitrary timestamp is not correct though, as it assumes that the gap between server UTC offset and user UTC offset is constant.

But it is far from guaranteed to be – and no, this isn’t a “technically, this could go wrong”. Even just the US and Europe switching to daylight savings time two weeks apart will break this assumption, and will make you select a time that is off by an hour (or, even more fun, just doesn’t exist). If you want to do datetime arithmetic, you’ll need to deal with timezones rather than offsets.

That said, with modern browsers, this is possible without resorting to library use: You can get the user’s timezone:

>>> Intl.DateTimeFormat().resolvedOptions().timeZone
"Europe/Berlin" 

Date is good enough to know not to generate invalid times – I tested this by adding an hour to the time of spring DST adjustment:

>>> d = new Date("2024-03-31T00:15:00Z")
>>> d.toLocaleString(undefined, {"timeZone": "Europe/Berlin"})
"31/03/2024, 01:15:00"
>>> d.setTime(d.getTime() + (60 * 60 * 1000))
>>> d.toLocaleString(undefined, {"timeZone": "Europe/Berlin"})
"31/03/2024, 03:15:00"

It can then also output a Date object in a chosen format and timezone:

>>> d.toLocaleString(undefined, {"timeZone": "Europe/Berlin"})
"31/03/2024, 03:15:00"
>>> d.toLocaleString(undefined, {"timeZone": "Australia/Adelaide"})
"31/03/2024, 11:45:00"

All this isn’t to say that this is what we should do, I just wanted to set the record straight re: current browser capabilities.

6 Likes