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

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️