What is the difference between toLocaleString, toLocaleDateString, and toLocaleTimeString?

Viewed 3865

Trying to read the documentation, but can't seem to find what, if anything, is the difference between these. They all seem to accept the same parameters and locales, and they seem to return the same values.

Are they just aliases of the same function? Or is there actually a difference between them?

const locale = 'no-nb'
const options = {
  day: '2-digit', month: 'long',
  hour: '2-digit', minute: '2-digit'
}

new Date().toLocaleString(locale, options)
"18. mai, 15"

new Date().toLocaleDateString(locale, options)
"18. mai, 15"

new Date().toLocaleTimeString(locale, options)
"18. mai, 15"
2 Answers

All of them give the exact same result if you provide custom format for at least one of the date elements (day, month, year) and at least one of the time elements (hour, minute, second).

They differ in their purpose and default behavior. Try skipping all custom time formats, for example:

new Date().toLocaleString('no-nb', {day: '2-digit'})
// 18

new Date().toLocaleDateString('no-nb', {day: '2-digit'})
// 18

new Date().toLocaleTimeString('no-nb', {day: '2-digit'})
// 18, 15:37:37

As you can see, toLocaleTimeString() always puts time in there, using default time format if you don't specify it.

toLocaleDateString() does the same thing, but for date instead of time:

new Date().toLocaleString('no-nb', {hour: '2-digit'})
// 15

new Date().toLocaleDateString('no-nb', {hour: '2-digit'})
// 18.05.2020, 15

new Date().toLocaleTimeString('no-nb', {hour: '2-digit'})
// 15

toLocaleString() allows you to format your date the way you like, it won't put anything extra.

As all the methods accept Intl.DateTimeFormat as options for constructing string so all of them will return the same strings for the same options.

However ECMA docs for all three clearly mention The contents of the String are implementation-dependent but the intention of methods are different and should be used as suggested.

toLocaleDateString

toLocaleString

toLocaleTimeString

Docs also say implementations that do not include ECMA-402 support must not use those parameter positions for anything else.

allowed options for each are as follows toLocaleString => "any", "all" from

toLocaleDateString => "date", "date" from

toLocaleTimeString => "time", "time" from

Related