DEV Community

Cover image for Native datetime formatter
Oleg Chursin
Oleg Chursin

Posted on

1 1

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:

// define formatter
const locales: string | string[] = 'en-US';
const options: Intl.DateTimeFormatOptions = {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit'
};
const formatter: Intl.DateTimeFormat = new Intl.DateTimeFormat(
locales,
options
);
// use
const date = new Date();
const formattedDate = formatter.format(date);

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay