George Song

Formatting Dates in JavaScript

July 10, 2020

Do you automatically reach for Moment.js when you need to format dates? Or perhaps you prefer date-fns? But if you have basic formatting needs, don’t discount the built-in JavaScript tools.

Use Case

I’m displaying a date with each article on this site. The source of the date is an ISO date string, which looks like 2022-09-22T18:54:23.296Z. This is a typical format you’ll receive as part of an API response, for example.

While the ISO format is explicit and great for cross-boundary data exchange, it’s not display-friendly. Let’s show a localized date string instead.

displays September 22, 2022

Solution

  1. Parse the ISO date string

    const isoDateString = "2020-07-10T14:16:40.463Z";
    const date = new Date(isoDateString);
  2. Get the browser locale

    const locale = typeof window === "undefined" ? "en" : navigator.language;

    If we’re not in a browser environment (window === "undefined"), default to English.

  3. Format the date

    const formattedDate = date.toLocaleDateString(locale, {
      year: "numeric",
      month: "long",
      day: "numeric",
    });

    See the Intl.DateTimeFormat() constructor for details on the parameters.

It’s a bit more code than using one of the libraries, but your users will thank you for the smaller bundle size.

OK, they probably won’t—but you’ll have the satisfaction of knowing you’ve done your part to improve their experience.

👩‍💻 Try It Out