Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
like image 417
Svish Avatar asked May 18 '20 13:05

Svish


1 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.

like image 87
Robo Robok Avatar answered Sep 17 '22 23:09

Robo Robok