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