Is there a way to display timestamp in unix format to ISODate?

♀尐吖头ヾ 提交于 2019-12-04 17:11:21

问题


We stored a date using unix timestamp in MongoDB, how do I get the date when I do the query? Is there a way to display timestamp in ISODate format?


回答1:


Background

  • A unixtime value represents seconds since the epoch (Jan 1, 1970).

  • A JavaScript Date() represents milliseconds since the epoch.

  • In MongoDB, ISODate() is a convenience wrapper for Date() that allows you to create dates from ISO strings in the mongo shell. If you use new Date() in the shell, it will return an ISODate().

Conversion

To convert between a unixtime and an ISODate() you can multiply your unix timestamps by 1000 and pass this value to the new Date() constructor.

A simple example in the mongo shell:

> db.mydata.insert({
    unixtime: 1362143511
})

> var doc = db.mydata.findOne();

// convert unixtime seconds to milliseconds and create JS date
> var date = new Date(doc.unixtime * 1000);

> date
ISODate("2013-03-01T13:11:51Z")



回答2:


In the Mongo console you can create a JavaScript Date object from a timestamp before the document is printed to the screen:

> db.stuff.find().forEach(function (doc) {
  doc["timestamp_field"] = new Date(doc["timestamp_field"])
  printjson(doc)
})

Be careful with that code, unlike a regular find() it will not page the results but print every matching document without pausing.




回答3:


Mongodb 4.0 has introduced $toDate aggregation, so you can try with it

db.collection.aggregate([
  { "$project": {
    "toDate": {
      "$toDate": "$unixTimestamp"
    }
  }}
])

Try it here



来源:https://stackoverflow.com/questions/15041953/is-there-a-way-to-display-timestamp-in-unix-format-to-isodate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!