How to Solve toLocaleDateString is not a Function in JavaScript
In this tutorial, we are going to learn about how to solve the TypeError: toLocaleDateString is not a function in JavaScript.
When we use a ‘toLocaleDateString()’ method on a value which is not a data type date object we will get the following error in our console.
Here is an example, how the error occurs:
const value = Date.now();
console.log(value); // unix timestamp
console.log(value.toLocaleDateString());
Output:
"TypeError: value.toLocaleDateString is not a function
In the example above, we are getting the error because we are using the ‘toLocaleDateString()’ method on a integer data type.
To solve the “TypeError: toLocaleDateString is not a function”, make sure to call the toLocaleDateString() method on a data type date object or convert the given value to a valid date object before calling the toLocaleDateString() method on it.
Here is an example:
const value = new Date();
const result = value.toLocaleDateString('en-US');
console.log(result);
Output:
"9/13/2023"
Other example:
const value = new Date();
const result = value.toLocaleDateString('ar-EG');
console.log(result);
Output:
"١٣/٩/٢٠٢٣"
In the example above, we have called the toLocaleDateString() method a valid date object. So, it returns the string representation of the current date in user locale. The toLocaleDateString() method is language sensitive and it uses the Intl.DateTimeFormat API.
Type checking
To avoid the run time errors, we can also check the given datatype is a object or not before calling the toLocaleDateString() method on it.
Here is an example:
const value = new Date();
if(typeof value === 'object' && value !== null && 'toLocaleDateString' in value){
console.log(value.toLocaleDateString());
}else{
console.log('Given value is not a Date object');
}
Conclusion
The “TypeError: toLocaleDateString is not a function” error occurs, when we call a ‘toLocaleDateString()’ method on a value which is not Date object. To solve the error, convert the value to an date object before calling the toLocaleDateString() method on it or make sure to use the toLocaleDateString() method on a valid date objects.