openstreetmap-ng / openstreetmap-ng

🗺️ The Next Generation of OpenStreetMap — in Python!
https://osm.ng
GNU Affero General Public License v3.0
154 stars 13 forks source link

Localize date timezone in frontend #130

Open Zaczero opened 1 day ago

Zaczero commented 1 day ago

Currently dates are in UTC timezone. As a NextGen platform, we should automatically convert such dates to local timezone before showing them on the site. I am not sure how to best approach it. Perhaps write some util method and standardize forms of dates in response HTML. Feel free to provide input on this issue if you have some experience with this :slightly_smiling_face:! Ideally, we should rely on browser APIs and have a zero-dependency system.

Dimitar5555 commented 1 day ago

The easiest way will be to wrap datetimes in time element and provide the timestamp (or whatever is used on the backend) in the datetime attribute (see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time).

date.toLocaleString(locale, options) can be used to convert it to convert the time to the local timezone and locale. It is widely supported across browsers and doesn't require much work from OSM-NG's side.

MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Browser support: https://caniuse.com/mdn-javascript_builtins_date_tolocalestring

Zaczero commented 1 day ago

datetime

We already use it in several places. It shouldn't be too hard to ensure it's present everywhere.

Date.toLocaleString(timestamp_in_ms, locale)

I presume we will need to write a simple JS utility function to perform the conversion? Maybe the time elements could hold an extra data-* attribute that would specify the formatting to use.

Dimitar5555 commented 9 hours ago

Sorry, I misled you. The actual syntax is date.toLocaleString(locale, options) where date is new Date(something). The formatting comes from the function automagically.

image

image

(note that it also changes the time to the user's timezone, if the timezone is specified in the input)

I presume we will need to write a simple JS utility function to perform the conversion? Maybe the time elements could hold an extra data-* attribute that would specify the formatting to use.

The function could be something like this:

function localise_dates() {
    const date_els = document.querySelectorAll('time');
    date_els.forEach(date_el => {
        let date = new Date(date_el.getAtribute('datetime'));
        data_el.innerText = date.toLocaleString(locale);
    });
}