JavaScript: Difference between toString() and toLocaleString() methods of Date

Viewed 21505

I am unable to understand the difference between the toString() and toLocaleString() methods of a Date object in JavaScript. One thing I know is that toString() will automatically be called whenever the Date objects needs to be converted to string.

The following code returns identical results always:

​var d = new Date();
document.write( d + "<br />" );
document.write( d.toString() + "<br />" );
document.write( d.toLocaleString() );

​ And the output is:

Tue Aug 14 2012 08:08:54 GMT+0500 (PKT)
Tue Aug 14 2012 08:08:54 GMT+0500 (PKT)
Tue Aug 14 2012 08:08:54 GMT+0500 (PKT)
5 Answers

Just to add. Apart from Date, it also converts/formats the normal variable. Both functions used to format/convert the passed parameter to string but how parameter is formatted is the point to look on.

toLocalestring() used to return the formatted string based on which geography the function is called.

For the sake of simplicity. Take this example. It shows how toString() won't format the variable but toLocaleSting() will format it based on locale setting of the geography.

let number = 1100;
console.log(number.toString()); // "1100"
console.log(number.toLocaleString())  // 1,100

let number = 1100;
console.log(number.toString());
console.log(number.toLocaleString());

It is a great help for programmer in order to avoid to write extra function to format the string or Date. toLocaleString() will take care of this.

Hope you would find it somewhat helpful & interesting.

Related