我无法通过以下方式获取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个调用.

Node.js相关问答推荐

Azure虚拟机上的JS Express:可疑请求?

如何修复PayPal Node.js Webhook中Webhook签名验证失败?''

Stripe webhook无法访问Express请求原始正文

为什么我的表单数据在我的POST请求中作为应用程序/json发送,为什么它返回错误请求错误?

无法使用Sequelize连接AWS RDS

Webpack:如何避免导出函数的重命名?

在 NodeJS 中使用 post 时出现错误 500TypeError: 无法解构 'req.body' 的属性 'name',因为它未定义

Promise 和 Azure 语音转文本

如何修复我的 NodeJS SSE 写入函数以在后续调用中更新 HTML?

将 null 推入管道后,node.js 可写完成未发出

Amplify 部署的应用程序出现TypeError: handler is not a function错误,但它在本地运行

Angular Build 生产返回致命的 javascript 无效大小错误

JavaScript & Node - 将图像文件保存到服务器但无法查看

为什么我在生产环境中 deproy Next.js 示例项目时 CSS 不起作用?

使用 $in 查询时,如何获取 mongoDB 中每个唯一 ID 的 n 个文档?

Node.js 服务器中没有缓存

如何将子集合添加到 Firestore 中的文档?

Node.js 中空函数的简写

为什么 Node.js 被命名为 Node.js?

expressjs app.VERB 调用中的 next() 和 next('route') 有什么区别?