6/8/2022, 11:37:17 AM
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:
Whereas in Hong Kong:
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
.