Dates in JavaScript simplified

JavaScript dates simplified

Dates, not only in JavaScript but in the whole programming context can get tricky sometimes. Earlier, I used switch cases and if/else for extracting month name and more but at one point I questioned “Is this modern code?”, I mean there’s gotta be a better way right?. Yes, there is something called ECMAScript Internationalization API more on that below.

Intl – Internationalization

Some properties like date and time can be language sensitive and comparing/converting them can be challenging. To overcome these types of problems the wise folks at ECMAScript set some standards to enable simple methods/properties to deal with time and date usage and formatting.

TLDR; In JavaScirpt we have the intl object that provides various methods to enable the date and time properties on a language-specific level. This makes it easier to format, compare and share information seamlessly.

toLocaleString()

All JavaScript date instances have a toLocaleString() method that can give us anything from a date object so let’s see how it works.

Syntax

dateObject.toLocaleDateString(locales, options)
The locale is a string like ‘en-US’ or ‘de-DE’

const date = new Date();
console.log(date.toLocaleString('default', {
    month: 'numeric'
}));
// 9
date.toLocaleString('default', {
    month: 'short'
});
// 'Sep'
date.toLocaleString('default', {
    month: 'long'
});
// 'September'

The best part is we can also pre-define our preferred format and pass it as an object for the options parameter.

const date = new Date();

const lang = 'en-US'

const options = {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric'
};

date.toLocaleString(lang, options);
// 'Sunday, September 19, 2021'

Converting strings to date

Sometimes we might obtain the date in the form of a string from an endpoint or any other source in that case we can parse it using the Date() method and obtain a JavaScript object.

const date = new Date('12 Oct 2021');
date.toLocaleString('en-US', {
    month: 'long'
}); // 'October'

Many formats

Using the above methods if we have a simple string say, 22 Jan 2021 we can convert it into various formats like:

  • Fri Jan 2021
  • Friday January 2021
  • 22 01 2021

The best part is the days/months can be printed in different languages

Conclusion

Browser support: Works on all browsers, except IE,
It’s 2021 and we have officially witnessed the death of the Internet Explorer,
Read more on Intl – Internationalization @MDN,
Isn’t this cool and simple? What do you think?

Tags: