DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Cover image for Native datetime formatter
Oleg Chursin
Oleg Chursin

Posted on

Native datetime formatter

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);
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Sweet. No deps. Just using the platform.


More info on MDN: DateTimeFormat

Top comments (0)

Another day as a dev

Stop by this week's meme thread!