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.
It's quite often you want to show a date in that user's specific format.
The outputs of today will vary 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.
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
Top comments (0)