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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay