Subscribe

Vanilla JavaScript date toLocaleString

✍️

Converting date object to locale dates in JavaScript

26 Mar, 2021 · 2 min read

Before we checked out how to convert numbers to locale formats using JavaScript, and today we’ll use the same approach but on date objects.

You often want to show a date in that user’s specific format.

Today’s outputs will vary depending on the locale we pass into the function.

JavaScript date to locale format

To use this function, we will first need a date object.

const date = new Date('01-10-2020');

This will give us a date format for the 1st of October 2020.

Depending on which locale your country uses, it might look different.

To use this function, we must call it upon our date object like so:

console.log(date.toLocaleDateString('en-US'));

That will give us the US annotation and return:

//'1/10/2020'

We can even specify some options on how we would like to receive the output.

const options = {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
};
console.log(date.toLocaleDateString('de-DE', options));

This will return:

//'Freitag, 10. Januar 2020'

JavaScript Date to different locales

You might have already spotted it above, but we can format it to different locales by setting the locale on the function.

console.log(date.toLocaleDateString('en-US'));
// '1/10/2020'
console.log(date.toLocaleDateString('en-GB'));
// '10/01/2020'
console.log(date.toLocaleDateString('ko-KR'));
// '2020. 1. 10.'
console.log(date.toLocaleDateString('ar-EG'));
// '١٠‏/١‏/٢٠٢٠'
console.log(date.toLocaleDateString('nl-NL'));
// '10-1-2020'

Pretty cool, right? If you are wondering where to find these locales, check out this locale list on Stackoverflow.

I’ve made this Codepen for you guys to play around with and see what happens when you change options or the locales.

See the Pen Vanilla JavaScript date toLocaleString by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter