How to Format Dates in JavaScript

For web applications especially, formatting a date is a pretty common task. Take a look at just about any website, whether it's an email client like Gmail, Twitter, or even on Stack Abuse articles, there is inevitably a date/time string somewhere on the page. In many cases, especially apps that have dynamically generated front-end content, the dates are formatted with JavaScript code. So I'd say it's safe to assume that this is a task you'll encounter fairly often.

Each of the following sections describes a method (or library) that you can use to format dates in JavaScript. Since there are a couple different ways to achieve this, I've listed them in order of my personal preference. However, you may find that one of the following solutions won't work for your application for one reason or another, in which case you can look further down the list for something that better suits your needs.

Moment.js

Moment.js is widely considered to be the best date-time library for JavaScript, and for good reason. It is extremely easy to use, well documented, and under 20kb (minified, gzipped) in size. It works with both Node.js and browser-side JavaScript, allowing you to use it throughout your entire codebase. This is a pretty big plus considering you only need to learn a single date-time library, regardless of whether you're programming the front or back-end.

Before we get in to formatting dates, let's use the Node REPL to check out a short moment primer:

> const moment = require('moment');
> let m = moment();                 // Create a new date, which defaults to the current time
> m = moment('2016-08-02 15:37');   // Parse an ISO 8601 date string
> m.month(9);                       // Set month to October - months are 0-indexed!

There are quite a few ways to create, parse, and manipulate dates with Moment, which we won't completely cover here. For a good overview of the library as a whole, check out our article, Moment.js: A Better Date Library for JavaScript.

Now that you know roughly how to use Moment to create and manipulate dates, let's see how to use it to format your dates as strings.

The simplest way to start is to use the .format() method with no arguments:

> moment().format();
'2016-08-02T15:44:09-05:00'

This will print out a date formatted in the ISO 8601 standard. However, unless you're printing the date to be saved in JSON or something similar, you probably don't want your users to have to deal with dates that look like that. Using format tokens, dates can be customized to your liking.

If you came to JavaScript from another language like Java or Python, then you'll likely be familiar with the concept of date formatting tokens. Although, a word of warning, don't assume the tokens from another language are exactly the same as those used in Moment. You should consult the docs first since there are quite a few differences.

With the .format() method, you can construct a string of tokens that refer to a particular component of a date (like day, month, minute, or am/pm).

For example, let's say you just want to see a simple representation of the current time (hours:minutes:seconds am/pm). We can achieve this with:

> moment().format('[The time is] h:mm:ss a');
'The time is 4:47:09 pm'

Here is a breakdown of the tokens you see above:

  • [The time is]: All text in brackets ([]) is ignored by the parser
  • h: Hours (no leading zero)
  • mm: Minutes (with leading zero)
  • ss: Seconds (with leading zero)
  • a: ante/post meridiem (am/pm)

All text enclosed in brackets and non-alphanumeric characters, like the colon characters (':'), are ignored by the parser. This way you can add formatting to your strings.

Format strings can get quite a bit more complicated than our example above. For example, if you want to print out the month, there are 5 ways to do so:

  • M: Month number (1, 2, 3... 12)
  • Mo: Month number with ordinal indicator (1st, 2nd, 3rd... 12th)
  • MM: Month number with leading zero (01, 02, 03... 12)
  • MMM: Month abbreviation (Jan, Feb, Mar... Dec)
  • MMMM: Month name (January, February, March... December)

The list of choices gets much longer when you consider the many variations for day of month, day of week, hour, year, etc. Once you learn the concept and play around with it a bit, the rest comes easy. Although it can be easy to forget tokens, so keep the reference handy when programming.

There is also some great support for both time zones and for customizing formatted dates by different locales. This typically isn't a big problem for small applications, but it can be a big pain for larger ones. If you need to support internationalization then Moment will be a lifesaver for you.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Moment is by far my favorite way to handle, manipulate, and format strings in JavaScript, so I'd highly suggest checking it out. Although, not everyone can stomach adding extra dependencies, especially for front-end development, which means you may need to try out one of the next two formatting options below.

The dateformat Package

dateformat is similar to Moment in that it formats dates using token strings, but it does so a bit differently. Using the browser version of datetime, it will extend the Date object to have a .format() method, which works much like Moment's format method:

Browser-side

today = new Date();
today.format('dd-m-yy');   // Returns '02-8-16'

With the Node.js version, it works a bit differently. Instead of extending Date.prototype to include format(), you must use dateformat as a method itself and pass your Date object:

Node.js

> const dateformat = require('dateformat');
> let now = new Date();
> dateformat(now, 'dddd, mmmm dS, yyyy, h:MM:ss TT');
'Tuesday, August 2nd, 2016, 5:45:19 PM'

Aside from how you call the formatting method, all of the token formatting works the same between the browser and Node.js versions.

One other benefit of using dateformat is its named formats. While everyone has their own preference as to how dates are formatted, there are really only a few different formats most people use. This library aims to avoid all of the duplication of work by providing common date formats by name:

Node.js

> const dateformat = require('dateformat');
> let now = new Date();
> dateformat(now, 'fullDate');
'Tuesday, August 2, 2016'
> dateformat(now, 'longTime');
'5:45:19 PM CDT'

Over 10 of these named formats are provided. Check out the documentation (linked above) to see a full list.

You also might find this library to be more suitable thanks to its small size. The file is only 1.2 KB when minified and gzipped. Not bad considering the benefit it provides.

Date.toLocaleString()

Now, while I don't recommend using this method, I know that based on project constraints this might be your only choice. It's also important to point this out considering this is the only built-in way to format date strings, so it may come in handy at some point down the road.

Using the built-in Date.toLocaleString() method is a dependency-free way to format your date-times. However, it isn't supported in Safari, and it's only supported in later versions of the other major browsers, so it might not be a good choice after all (unless you're using Node). Anyhow, let's see how it works.

Instead of using token strings like in the libraries above, here we use an options object where each part of your date can be configured.

For example, instead of mm for a 2-digit hour, we'd use {hour: '2-digit'}. The same goes for all other components of a date, like weekday, year, month, day, etc.

let now = new Date();

let options = {
    weekday: 'long',
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
};

now.toLocaleString('en-us', options);   // Returns 'Tuesday, Aug 2, 2016, 6:03 PM'

As you can see, using the .toLocaleString() method is much more verbose than the other formatting methods we've seen throughout this article.

Some of the more common date components you can set in the options object (and their possible values) are:

  • weekday: narrow, short, long
  • year: numeric, 2-digit
  • month: numeric, 2-digit, narrow, short, long
  • day: numeric, 2-digit
  • hour: numeric, 2-digit
  • minute: numeric, 2-digit
  • second: numeric, 2-digit

The same formatting effect can be accomplished with .toLocaleString(), but it just takes a bit more effort.

Conclusion

JavaScript/Node.js have quite a few libraries that can format date strings for you, but I only showed a few of the more popular methods in this article. Each has its own advantages, so you should evaluate which one works best for you.

Which date-time library do you prefer? Are there any not mentioned here that should have been? Let us know in the comments!

Last Updated: July 10th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms