JavaScript Date.valueOf() Method
-
Syntax of JavaScript
Date.valueOf()
: -
Example Code: Use the
date.valueOf()
Method to Get the Primitive Value of a Date Object -
Example Code: Use the
date.valueOf()
Method to Check the Difference in Primitive Values of Two Date Objects
date.valueOf()
can get the primitive value of a date object after finding the difference in milliseconds between the mentioned date and 1st January 1970.
Syntax of JavaScript Date.valueOf()
:
let date = new Date();
date.valueOf();
Parameter
This method does not take any parameters.
Return
This method returns a number in milliseconds after calculating the difference between the date mentioned in a date object and 1st January 1970.
Example Code: Use the date.valueOf()
Method to Get the Primitive Value of a Date Object
In JavaScript, we can use the date.valueOf()
method for the primitive value of a date object.
We created a date object in this example using the new Date()
method. To get the difference in milliseconds between 1st January 1970 and the given date in the date object, we used the date.valueOf()
method.
let dateObj = new Date(2022,8,20);
let value = dateObj.valueOf();
console.log(value);
Output:
1663632000000
Example Code: Use the date.valueOf()
Method to Check the Difference in Primitive Values of Two Date Objects
There are different ways to enter a date in a date object. However, the output can change if the placement of year, month, and day are placed incorrectly.
We will use the date.valueOf()
method to see the difference between two date objects with the same date. The dates are placed correctly in the first date object, and the month and day are placed incorrectly in the other one.
var date=new Date(2022, 7, 15);
let val = date.valueOf();
console.log(val);
let d = new Date(2022, 15, 7);
let value = d.valueOf();
console.log(value);
Output:
1660521600000
1680825600000
The date.valueOf()
method can be used in most browsers. We can use this method to get the primitive value of a date object displayed as text.