我无法通过以下方式获取MongoDB记录的JavaScript日期字符串.它一直在使用我的本地时间.
var utc = moment.utc().valueOf();
console.log(moment.utc(utc).toDate());
输出:
Tue Nov 11 2014 14:42:51 GMT-0500 (EST)
我需要UTC格式,这样我就可以在Mongo中粘贴这个时间戳,这样类型就可以是Date
.
我该怎么做?
我无法通过以下方式获取MongoDB记录的JavaScript日期字符串.它一直在使用我的本地时间.
var utc = moment.utc().valueOf();
console.log(moment.utc(utc).toDate());
输出:
Tue Nov 11 2014 14:42:51 GMT-0500 (EST)
我需要UTC格式,这样我就可以在Mongo中粘贴这个时间戳,这样类型就可以是Date
.
我该怎么做?
时间戳是一个时间点.通常,这可以用超过epoc(1970年1月1日上午12点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
以毫秒计,每一个都是相同的.这是完全相同的时间点(尽管在某些运行中,后面的毫秒要高一个).
就格式而言,每种格式都可以在特定的时区中表示.对于完全相同的时间点,时区字符串的格式看起来不同!
你要比较这些时间值吗?只要转换成毫秒.毫秒的一个值始终小于、等于或大于另一个毫秒值.
你想比较特定的"小时"或"天"值,并担心它们"来自"不同的时区吗?首先使用moment.utc( existingDate )
转换为UTC,然后进行操作.这些转换的示例,当从数据库中出来时,是示例中的最后console.log
个调用.