Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting isodate to numerical value

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?

like image 821
zeferino Avatar asked Sep 19 '13 13:09

zeferino


People also ask

How to convert iso time to date?

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.

How to get timestamp from 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.


1 Answers

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") }
like image 185
Xavier Guihot Avatar answered Oct 21 '22 00:10

Xavier Guihot