MomentJS以UTC获取JavaScriptdate

我无法通过以下获取MongoDBlogging的JavaScriptdatestring。 它继续使用我当地的时间。

var utc = moment.utc().valueOf(); console.log(moment.utc(utc).toDate()); 

输出:

 Tue Nov 11 2014 14:42:51 GMT-0500 (EST) 

我需要它在UTC,所以我可以坚持这个时间戳在Mongo,所以types将是Date

我怎样才能做到这一点?

时间戳是一个时间点。 通常情况下,这可以通过epoc(1970年1月1日12AM UTC的Unix Epoc)数毫秒来表示。 该时间点的格式取决于时区。 虽然时间点相同,但“时间值”在时区之间并不相同,必须考虑到UTC的偏移量。

这里有一些代码来说明。 关键是时间是以三种不同的方式捕捉的。

 var moment = require( 'moment' ); var localDate = new Date(); var localMoment = moment(); var utcMoment = moment.utc(); var utcDate = new Date( utcMoment.format() ); //These are all the same console.log( 'localData unix = ' + localDate.valueOf() ); console.log( 'localMoment unix = ' + localMoment.valueOf() ); console.log( 'utcMoment unix = ' + utcMoment.valueOf() ); //These formats are different console.log( 'localDate = ' + localDate ); console.log( 'localMoment string = ' + localMoment.format() ); console.log( 'utcMoment string = ' + utcMoment.format() ); console.log( 'utcDate = ' + utcDate ); //One to show conversion console.log( 'localDate as UTC format = ' + moment.utc( localDate ).format() ); console.log( 'localDate as UTC unix = ' + moment.utc( localDate ).valueOf() ); 

哪个输出这个:

localData unix = 1415806206570 localMoment unix = 1415806206570 utcMoment unix = 1415806206570 localDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST) localMoment string = 2014-11-12T10:30:06-05:00 utcMoment string = 2014-11-12T15:30:06+00:00 utcDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST) localDate as UTC format = 2014-11-12T15:30:06+00:00 localDate as UTC unix = 1415806206570

就毫秒而言,每个都是一样的。 这是完全相同的时间点(尽pipe在一些运行中,后面的毫秒是更高的)。

就格式而言,每个都可以在特定的时区中表示。 而且这个时区的string的格式看起来不一样,时间也是一样的!

你打算比较这些时间值吗? 只需转换为毫秒。 一个毫秒值总是小于,等于或大于另一个毫秒值。

你想比较具体的“小时”还是“日”的值,并担心他们“来自”不同的时区? 首先使用moment.utc( existingDate )转换为UTC,然后执行操作。 这些转换的例子,当从数据库中出来时,就是这个例子中的最后一个console.log调用。

调用toDate将创build底层JS Date对象的副本 (文档是错误的,而不是副本)。 JSdate对象以UTC格式存储,并始终打印到东部时间。 不考虑是否.utc()修改时间包装的底层对象使用下面的代码。

你不需要这个时刻。

 new Date().getTime() 

这是有效的,因为它的核心JS Date来自Unix Epoch的UTC。 这是非常混乱,我相信在这个接口混合本地和UTC时间的一个很大的缺陷,没有在方法中的描述。