Convert a Full Date to a Short Date in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Convert a Full Date to a Short Date in JavaScript #

Use the toLocaleDateString() method to convert a full date to a short date. The method takes the locale and an options object as parameters and returns a string that represents the date according to the provided locale and options.

index.js
const date = new Date('2022-09-24'); // 👇️ "09/24/2022" console.log( date.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', }), );

The toLocaleDateString() method returns a string representation of the date according to the provided parameters.

The two parameters we passed to the method are:

  1. locales - a string with a BCP 47 language tag or an array of such strings. You can use any of the available locales, e.g. es-MX for Mexico or en-CA for Canada. If you need more information about this parameter, check out the MDN docs.
  2. options object, where we can adjust the formatting style. Read more about the options object in the MDN docs.

The example above gets the short date using the en-US locale. However, you can use the visitor's default locale by passing an empty array for the locales parameter.

index.js
// 👇️ use visitor's default locale console.log( date.toLocaleDateString([], { year: 'numeric', month: '2-digit', day: '2-digit', }), );
The example above uses the visitor's default locale. In other words, the formatting of the short date would vary depending on the user's preferred locale.

The year property can be set to:

  • numeric - e.g. 2022
  • 2-digit - e.g. 22

The month property can be set to:

  • numeric - e.g. 9
  • 2-digit - e.g. 09
  • long - e.g. September
  • short - e.g. Sep
  • narrow - e.g. S

The day property can be set to:

  • numeric - e.g. 4
  • 2-digit - e.g. 04

Depending on the locale you pass to the function, the formatting of the short date may vary.

Some locales add a leading zero if the values for the day or month are less than 10 and others don't.

Setting the month and day properties to 2-digits enables us to always produce consistent results.

You can also set the weekday property if you want to display the name of the weekday.

index.js
// 👇️ "Sat, 09/24/2022" console.log( date.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short', }), );

The weekday property can be set to:

  • long - e.g. Thursday
  • short - e.g. Thu
  • narrow - e.g. T

When the narrow formatting is used for the month, two months may have the same narrow style for some locales, e.g. July and June are both represented as J.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.