JavaScript Date valueOf()
Syntax & Examples
Date.valueOf() method
The valueOf() method of the Date object in JavaScript returns the primitive value of a Date object as the number of milliseconds since January 1, 1970, 00:00:00 UTC. This method overrides the Object.prototype.valueOf() method.
Syntax of Date.valueOf()
The syntax of Date.valueOf() method is:
valueOf()
This valueOf() method of Date returns the primitive value of a Date object. Overrides the Object.prototype.valueOf() method.
Return Type
Date.valueOf() returns value of type Number
.
✐ Examples
1 Using valueOf() to get the primitive value of a Date object
In JavaScript, we can use the valueOf()
method to get the primitive value of a Date object as the number of milliseconds since January 1, 1970, 00:00:00 UTC.
For example,
- We create a new Date object
date
representing January 1, 2000. - We use the
valueOf()
method to get the primitive value of thedate
object. - The primitive value is stored in the variable
primitiveValue
. - We log
primitiveValue
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date('2000-01-01T00:00:00Z');
const primitiveValue = date.valueOf();
console.log(primitiveValue);
Output
946684800000
2 Using valueOf() with a specific date
We can use the valueOf()
method to get the primitive value of a specific Date object.
For example,
- We create a new Date object
date
representing July 4, 1776. - We use the
valueOf()
method to get the primitive value of thedate
object. - The primitive value is stored in the variable
primitiveValue
. - We log
primitiveValue
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date('1776-07-04T00:00:00Z');
const primitiveValue = date.valueOf();
console.log(primitiveValue);
Output
-6106063200000
3 Using valueOf() with the current date
We can use the valueOf()
method to get the primitive value of the current date.
For example,
- We create a new Date object
date
representing the current date and time. - We use the
valueOf()
method to get the primitive value of thedate
object. - The primitive value is stored in the variable
primitiveValue
. - We log
primitiveValue
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date();
const primitiveValue = date.valueOf();
console.log(primitiveValue);
Output
Depends on the current date and time (e.g., '1685211296789')
Summary
In this JavaScript tutorial, we learned about valueOf() method of Date: the syntax and few working examples with output and detailed explanation for each example.