The simpler the better. Here's a dead simple date formatter snippet that works in all modern browsers as well as node apps.
// define formatter
const locale = 'en-US';
const options = {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit'
};
const formatter = new Intl.DateTimeFormat(locale, options);
// use
const date = new Date();
const formattedDate = formatter.format(date);
Typed version is also here:
What's going on above? We grab the current date with new Date()
, instantiate the formatter with Intl.DateTimeFormat
providing the locale string and date format options object.
Tiny playground file:
datetime-format.js
const date = new Date();
const locales = ['en-US', 'en-GB', 'en-CA'];
const options = {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit'
};
for (let locale of locales) {
const formatter = new Intl.DateTimeFormat(locale, options);
const formattedDate = formatter.format(date);
console.log(`formattedDate: ${locale} -->`, formattedDate);
}
Running it in node will produce the following result:
~/dev/node-playground » node datetime-format.js
formattedDate: en-US --> Dec 16, 2021, 2:28 AM
formattedDate: en-GB --> 16 Dec 2021, 2:28
formattedDate: en-CA --> Dec. 16, 2021, 2:28 a.m.
Sweet. No deps. Just using the platform.
More info on MDN: DateTimeFormat
Top comments (0)