Converting isodate to numerical value

16,374

Solution 1

Simply call the getTime() method, and you get the milliseconds since 1970/01/01

> var date_test = ISODate ("2013-07-26T22:35:40.373Z")
> date_test.getTime()
1374878140373

to convert milliseconds into date back, construct a new date object:

> new Date(1374878140373)
ISODate("2013-07-26T22:35:40.373Z")

Solution 2

Starting Mongo 4.0, the $toLong aggregation operator can be applied on a Date to get a timestamp:

// { mydate: ISODate("2019-06-23T15:52:29.576Z")
db.collection.aggregate({ $project: { timestamp: { $toLong: "$mydate" } } })
// { timestamp: NumberLong("1561305149576") }

and vice versa with $toDate:

// { timestamp: NumberLong("1561305149576") }
db.collection.aggregate({ $project: { mydate: { $toDate: "$timestamp" } } })
// { mydate: ISODate("2019-06-23T15:52:29.576Z") }
Share:
16,374
zeferino
Author by

zeferino

Updated on July 18, 2022

Comments

  • zeferino
    zeferino almost 2 years

    I am performing tests to ensure I'm getting the dates correctly.

    My current tests are: pick a date in mongodb ISODate format and transform it to the numerical value (milliseconds since 1970) and vice versa

    Example:

    var date_test = ISODate ("2013-07-26T22:35:40.373Z")
    

    What is the numeric value of this date? Which command is used to get this?

  • zeferino
    zeferino over 10 years
    I get "19:35:40 GMT-0300 (BRT)" when typing date_test.toTimeString()