Last updated: Mar 2, 2024
Reading timeยท2 min
The "TypeError: date.getDate is not a function" occurs when the getDate()
method is called on a value that is not a date object.
To solve the error, convert the value to a date before calling the method or
make sure to only call the getDate()
method on valid date objects.
Here is an example of how the error occurs.
const date = Date.now(); console.log(date); // ๐๏ธ 1639... // โ๏ธ TypeError: date.getDate is not a function const result = date.getDate();
The Date.now()
function returns an integer, so we cannot call the
Date.getDate()
method on it.
getDate()
method on valid date objectsTo solve the error, make sure to only call the getDate()
method on valid date
objects.
const d1 = new Date().getDate(); console.log(d1); // ๐๏ธ 26 const d2 = new Date('Sept 24, 22 13:20:18').getDate(); console.log(d2); // ๐๏ธ 24
You can get a date object by passing a valid date to the Date() constructor.
If an invalid date is passed to the Date()
constructor, you will get NaN
(not a number) value back.
const d1 = new Date('invalid').getDate(); console.log(d1); // ๐๏ธ NaN
You can console.log
the value you are calling the getDate
method on and see
if it's a valid Date
object.
Date
object before calling getDate()
You could conditionally check if the value is a Date
object in the following
way.
const d1 = new Date(); if (typeof d1 === 'object' && d1 !== null && 'getDate' in d1) { const result = d1.getDate(); console.log(result); // ๐๏ธ 16 }
Our if
condition uses the logical AND (&&) operator, so for the if
block to
run, all of the conditions have to be met.
d1
variable stores a value with a type of object because dates have a type of object.Then we
check if the variable is not equal to null.
Unfortunately, if you check the type of null with console.log(typeof null)
,
you will get an "object"
value back, so we have to make sure the value is not
null
.
getDate
property.Then we know we can safely call the getDate()
method on the object.
This approach is called duck-typing.
When using duck-typing, we simply check if the object implements specific properties or methods and if it does, we assume it's an object of the correct type.