Skip to content

Instantly share code, notes, and snippets.

@julianlam
Created June 8, 2022 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianlam/33569f7da9a1046496e273960562b8dc to your computer and use it in GitHub Desktop.
Save julianlam/33569f7da9a1046496e273960562b8dc to your computer and use it in GitHub Desktop.
Testing `datetime-local` input across various locales #blog

Working with <input type="datetime-local"> is a lot of fun. All major browsers have standardized their UIs, and offer full support, and so the days of using polyfills or jQuery fallbacks are numbered.

Should you need support for older or more esoteric browsers, it may be best to fall back to a bunch of <select> inputs instead.

The cool thing about datetime-local is that the UI itself is localised based on the user's browser/machine language settings.

For example, in Canada:

image

Whereas in Hong Kong:

image

Neat!

In all cases, the value associated with the input is of consistent format, an ISO string in the user's local timezone:

document.querySelector('input[type="datetime-local"]').value;

// "2022-06-02T22:00" 

Converting this to a UNIX timestamp is straightforward. Toss it into new Date() and call .getTime():

new Date("2022-06-02T22:00").getTime();
// 1654221600000 

You'll want to ensure that the value you pass into new Date() is an actually parseable. If not, the resulting date object is "Invalid Date". You can test this by passing the resulting date object to isNaN().

const a = new Date("2022-06-02T22:00");
isNaN(a);  // false, so we're ok

Back to the issue at hand—how do we test the frontend interface across different languages?

In Firefox, go to about:config and modify intl.locale.requested to read whichever language you want (e.g. pt-BR, en-US, fr, etc.)

You can confirm the change by looking at the browser UI (which should switch languages if applicable), or calling Intl.DateTimeFormat().resolvedOptions().locale.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment