How to format dates in React app?

When working with dates in React, it is essential to properly format them to avoid confusion, especially when dealing with different languages and locales. This is because different cultures may have their own unique ways of displaying dates, such as the order of the day, month, and year, or the use of separators such as dots or slashes.

Fortunately, JavaScript provides a built-in Intl object that can help with formatting dates according to the user's locale. This object offers a variety of options for customizing the date format, such as specifying the date and time styles, selecting the calendar type, and choosing the language and region.

let date = new Date('2023-02-08T00:00:00');

let enFormatter = new Intl.DateTimeFormat('en-US');
console.log(enFormatter.format(date)); // 2/8/2023

let esFormatter = new Intl.DateTimeFormat('es-ES');
console.log(esFormatter.format(date)); // 8/2/2023

If you want to learn more about formatting dates in React, there are two articles you can check out. One covers the built-in JavaScript Intl object, while the other explores using third-party libraries like react-intl to provide more advanced formatting options and better support for various locales and time zones.

React internationalization tutorial:

Copyrights 2024 © Localizely