我无法通过以下方式获取MongoDB记录的JavaScript日期字符串。它一直在用我的当地时间。
var utc = moment.utc().valueOf();
console.log(moment.utc(utc).toDate());
输出:
Tue Nov 11 2014 14:42:51 GMT-0500 (EST)
我需要它是世界协调时,所以我可以坚持这个时间戳在Mongo中,这样类型就会是Date
。
我该怎么做呢?
发布于 2014-11-12 23:32:15
时间戳是一个时间点。通常,这可以用超过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
就毫秒而言,每个都是相同的。这是完全相同的时间点(尽管在某些运行中,后一毫秒要高出一毫秒)。
就格式而言,每种格式都可以用特定的时区表示。对于完全相同的时间点,该时区字符串的格式看起来是不同的!
您要比较这些时间值吗?只需转换为毫秒即可。一个毫秒值始终小于、等于或大于另一个毫秒值。
您是否希望比较特定的“小时”或“天”值,并担心它们“来自”不同的时区?首先使用moment.utc( existingDate )
转换为UTC,然后执行操作。这些转换的示例是示例中的最后一次console.log
调用。
发布于 2021-05-05 16:36:37
这将为您提供协调时区DateTime。
var convertedUtcDateTime = moment.utc(dateTimeToBeConverted);
https://stackoverflow.com/questions/26873200
复制相似问题