Converting isodate to numerical value in MongoDB?

In MongoDB, you can convert an ISODate to a numerical value (milliseconds since Unix epoch) using the getTime() method. This returns the timestamp as a number, which is useful for calculations and comparisons.

Syntax

yourDateVariable.getTime()

Example

Let's create an ISODate and convert it to a numerical value ?

var arrivalDate = ISODate('2019-04-18 13:50:45');

Now convert the ISODate to numerical value ?

arrivalDate.getTime();
1555595445000

Verify Result

To verify this is correct, convert the number back to ISODate ?

new Date(1555595445000);
ISODate("2019-04-18T13:50:45Z")

Key Points

  • getTime() returns milliseconds since January 1, 1970 UTC
  • The numerical value can be used for date arithmetic and comparisons
  • Use new Date(number) to convert back to ISODate format

Conclusion

The getTime() method efficiently converts MongoDB ISODate objects to numerical timestamps. This conversion is particularly useful for date calculations and storing timestamps in a more compact format.

Updated on: 2026-03-15T00:47:21+05:30

511 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements