George Song

Formatting Dates in JavaScript

Do you automatically reach for Moment.js or date-fns when formatting dates? For basic needs, consider the built-in JavaScript tools instead.

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 2025-04-20T19:15:25.550Z. This is a common format you’ll receive from APIs.

While ISO format is excellent for data exchange, it’s not user-friendly for display. Let’s localize it instead.

displays April 20, 2025

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 (like during SSR), 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