How to Format Dates with Vanilla JavaScript

How to Format Dates with Vanilla JavaScript

ยท

5 min read

This post is a product of a problem I was trying to solve while working on the "Blog" section of my new website. I was referencing an article that describes how to show blog posts on your personal website. After successfully querying the data I realized that the dateAdded property was formatted one way and I wanted it to be displayed in a reader-friendly format. Throughout this article, I will explain my process of getting to a solution with vanilla JavaScript.

The Problem

The date being returned back is in the standard ISO format. As an example, the value for one of my blog posts is "2020-10-09T06:17:30.511Z". However, I want to display the date in a Month Day, Year format. This would mean that the example date I just provided would get transformed to display: October 9, 2020.

I know that there are libraries out there that do this for you, but I wanted to try and tackle this issue without the aid of third-party libraries since my use case for date formatting is limited to one particular area of my site.

My Original Solution

My first pass at solving the problem looked something like this:

const getFormattedDate = (date) => {
    const newDate = new Date(date) 
    const monthString = new Intl.DateTimeFormat('en-US', 
     { month: 'long'}).format(newDate)

    const day = newDate.getDate()
    const year = newDate.getFullYear()  
    return `${monthString} ${day}, ${year}`
}

The last two lines before the return utilize JavaScript's Date methods to grab the day and year. However, the second line that utilizes the Intl.DateTimeFormat() was something new to me. As I started digging into the specifications, I learned that there were more advanced capabilities available and that I could use them to condense my code down even further.

Intl.DateTimeFormat()

According to the MDN Docs

The Intl.DateTimeFormat object is a constructor for objects that enable language-sensitive date and time formatting.

The constructor takes two optional parameters:

  1. locales
  2. options

The first parameter, locales, is a string representation that defines a user's language and region. (For example, en-US for US English). If you want to use the browser's default locale you can either omit this parameter altogether or pass in undefined.

The second parameter, options, accepts an object that allows you to customize the date and time formats based on certain settings. Because I wanted the date to be displayed in the Month Day, Year format I went with the {dateStyle: "long"} option.

There are way too many options for me to list out in this article but definitely check out the docs for an exhaustive list of properties to choose from.

The format() Function

Each Intl.DateTimeFormat() object has a corresponding format(date) getter function. This method requires a JS Date as a parameter and it can be leveraged to format said date into a string that is formatted according to the locale and options that were passed in as params to the original Intl.DateTimeFormat() object.

I'll provide an example in the next section demonstrating how this works in tandem with the Intl.DateTimeFormat object we discussed in the previous section.

Take Deux ๐ŸŽฌ

  1. Create a Date object from the date argument in the function and assign it to a variable.
  2. Return an instance of the Intl.DateTimeFormat()object and pass in the desired locale and options as parameters.
  3. Chain the format() method to this object and pass in the Date object defined in Step #1.
const getFormattedDate = (date) => {
  const newDate = new Date(date); //Step 1
  return new Intl.DateTimeFormat("en-US", { //Step 2
    dateStyle: "long",
  }).format(newDate); //Step 3
};

The final product looks like this on my website:

Screen Shot 2020-10-10 at 5.11.58 PM.png

Browser Compatibility

At the time of this writing, browser compatibility is not consistent for some of the options values like dateStyle, especially as it pertains to Edge and Safari. It's not a huge deal for my use case, but keep this in mind when reaching for these types of settings.

However, the actual DateTimeFormat() constructor itself along with a lot of other options values are still compatible across all modern browsers so this is still a very powerful and compatible utility.

El Fin ๐Ÿ‘‹๐Ÿฝ

With popular libraries like momentjs announcing that they're a legacy project in maintenance mode, it's nice to know that there are native JS methods that allow you to do some convenient date and time formatting. I hope this proves to be a useful nugget of information the next time you need to deal with handling dates on the front-end.

If you enjoy what you read, feel free to like this article or subscribe to my newsletter, where I write about programming and productivity tips.

As always, thank you for reading and happy coding!

Resources

[Photo by Monica Sauro on Unsplash]