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?
Use the Date() constructor to convert an ISO string to a date object, e.g. new Date('2023-07-21T09:35:31.820Z') . The Date() constructor will easily parse the ISO 8601 string and will return a Date object. Copied! We used the Date() constructor to create a Date object from an ISO string.
Use the getTime() method to convert an ISO date to a timestamp, e.g. new Date(isoStr). getTime() . The getTime method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation.
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") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With