mongodb 有没有办法以unix格式将时间戳显示到ISODate?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15041953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to display timestamp in unix format to ISODate?
提问by Adam Lee
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?
我们在 MongoDB 中使用 unix 时间戳存储了一个日期,我如何在查询时获取日期?有没有办法以 ISODate 格式显示时间戳?
回答by Stennie
Background
背景
A unixtimevalue represents secondssince the epoch (Jan 1, 1970).
A JavaScript Date()represents millisecondssince the epoch.
In MongoDB,
ISODate()
is a convenience wrapper forDate()
that allows you to create dates from ISO strings in themongo
shell. If you usenew Date()
in the shell, it will return anISODate()
.
甲unixtime值表示秒,因为历元(1970年1月1日)。
甲JavaScript的日期()表示毫秒,因为时代。
在 MongoDB 中,它
ISODate()
是一个方便的包装器Date()
,允许您在mongo
shell 中从 ISO 字符串创建日期。如果new Date()
在 shell 中使用,它将返回一个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.
要在 aunixtime
和 ISODate()之间进行转换,您可以将您的 unix 时间戳乘以 1000 并将此值传递给new Date()
构造函数。
A simple example in the mongo
shell:
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")
回答by Theo
In the Mongo console you can create a JavaScript Date
object from a timestamp before the document is printed to the screen:
在 Mongo 控制台中,您可以Date
在文档打印到屏幕之前根据时间戳创建一个 JavaScript对象:
> 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.
请注意该代码,与常规代码不同,find()
它不会对结果进行分页,而是在不暂停的情况下打印每个匹配的文档。