Javascript 从 Mongodb 格式化 ISODate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11486779/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:01:33  来源:igfitidea点击:

Formatting ISODate from Mongodb

javascriptnode.jsmongodbisodate

提问by jamjam

In Mongodb I am storing date and time in ISODate format.

在 Mongodb 中,我以 ISODate 格式存储日期和时间。

Which looks like this

看起来像这样

ISODate("2012-07-14T01:00:00+01:00")

Using nodejs/javascript, how can I display the time component so I would get something like this

使用 nodejs/javascript,我怎样才能显示时间组件,所以我会得到这样的东西

Time : 01:00

I am using momentjs to make this easier but from what I can tell momentjs does seem to support the ISODate format.

我正在使用 momentjs 来简化此操作,但据我所知,momentjs 似乎确实支持 ISODate 格式。

Thanks for you help.

谢谢你的帮助。

回答by Sarah Roberts

JavaScript's Date object supports the ISO date format, so as long as you have access to the date string, you can do something like this:

JavaScript 的 Date 对象支持 ISO 日期格式,因此只要您可以访问日期字符串,就可以执行以下操作:

> foo = new Date("2012-07-14T01:00:00+01:00")
Sat, 14 Jul 2012 00:00:00 GMT
> foo.toTimeString()
'17:00:00 GMT-0700 (MST)'

If you want the time string without the seconds and the time zone then you can call the getHours() and getMinutes() methods on the Date object and format the time yourself.

如果您想要没有秒和时区的时间字符串,那么您可以调用 Date 对象上的 getHours() 和 getMinutes() 方法并自己格式化时间。

回答by Stennie

MongoDB's ISODate()is just a helper function that wraps a JavaScript date object and makes it easier to work with ISO date strings.

MongoDB 的ISODate()只是一个辅助函数,它包装了一个 JavaScript 日期对象,使处理 ISO 日期字符串变得更容易。

You can still use all of the same methods as working with a normal JS Date, such as:

您仍然可以使用与使用普通 JS Date 相同的所有方法,例如:

ISODate("2012-07-14T01:00:00+01:00").toLocaleTimeString()

// Note that getHours() and getMinutes() do not include leading 0s for single digit #s
ISODate("2012-07-14T01:00:00+01:00").getHours()
ISODate("2012-07-14T01:00:00+01:00").getMinutes()

回答by Jin Thakur

you can use mongo query like this yearMonthDayhms: { $dateToString: { format: "%Y-%m-%d-%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

你可以像这样使用 mongo 查询 yearMonthDayhms: { $dateToString: { format: "%Y-%m-%d-%H-%M-%S", date: {$subtract:["$cdt",14400000] }}}

HourMinute: { $dateToString: { format: "%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

时分:{ $dateToString:{ 格式:"%H-%M-%S",日期:{$subtract:["$cdt",14400000]}}}

enter image description here

在此处输入图片说明

回答by user3684669

// from MongoDate object to Javascript Date object

var MongoDate = {sec: 1493016016, usec: 650000};
var dt = new Date("1970-01-01T00:00:00+00:00");
    dt.setSeconds(MongoDate.sec);