How to Solve date.getUTCDate is not a Function in JavaScript
In this tutorial, we are going to learn about how to solve the TypeError: date.getUTCDate is not a function in JavaScript.
When we call a ‘getUTCDate()’ 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 date = Date.now();
console.log(date); // unix timestamp
console.log(date.getUTCDate());
Output:
"TypeError: date.getUTCDate is not a function
In the example above, we are getting the error because we are using the ‘getUTCDate()’ method on a integer data type, but the getUTCDate method is only available on a date object.
To solve the “TypeError: date.getUTCDate is not a function”, make sure to call the getUTCDate() method on a data type date object or convert the given value to a valid date object before calling the getUTCDate() method on it.
Here is an example:
const date = new Date();
const result = date.getUTCDate();
console.log(result);
Output:
26
In the example above, we have called the getUTCDate() method a valid date object. So, it returns the string representation of the current date according to universal time.
Type checking
To avoid the run time errors, we can also check if the given datatype is a object or not before calling the getUTCDate() method on it.
Here is an example:
const value = new Date();
if(typeof value === 'object' && value !== null && 'getUTCDate' in value){
console.log(date.getUTCDate());
}else{
console.log('Given value is not a Date object');
}
Conclusion
The “TypeError: date.getUTCDate is not a function” error occurs, when we call a getUTCDate() method on a value which is not Date object. To solve the error, convert the value to an date object before calling the getUTCDate() method on it or make sure to use the getUTCDate() method on a valid date objects.