David Ho
David Ho

Reputation: 5

Does .toLocaleDateString() automatically format date based on location?

If I run new Date().toLocaleDateString(), I receive "1/16/2020.
If someone in a country with the date format of DD/MM/YYYY (16/1/2020) ran my code, would it automatically swap the day and month?

Upvotes: 0

Views: 1124

Answers (1)

Tyler Roper
Tyler Roper

Reputation: 21672

If you do not specify a locale argument, then the result is based on the user's browser default locale. While this may correspond to location more often than not, it is not guaranteed to match their current location. It is a user preference.

For example, a British person living abroad in the US may choose to set their browser locale to en-GB. In this case, .toLocaleDateString() would return the date as DD/MM/YYYY despite the user being in the US.

You can determine a user's current locale through the Navigator interface:

const getBrowserLocale = () => navigator.language || navigator.browserLanguage || (navigator.languages || ["en"])[0]

console.log( getBrowserLocale() );

For more info, see the docs: .toLocaleDateString()

Upvotes: 1

Related Questions