【问题标题】:Timezone mismatch in MeteorJS and MomentJS insert and findMeteorJS 和 MomentJS 中的时区不匹配插入和查找
【发布时间】:2015-10-26 01:09:05
【问题描述】:

我正在将日期添加到名为 Meals 的 Meteor 集合中。日期是用餐日期,当我刷新出版物时,它显示前一天作为用餐日期。餐点添加在 Meteor.method 中,包括:

        // pick out the whitelisted keys
    var item = {
        name  : postAttributes.name,
        date : moment(postAttributes.date).utc().toDate(),
        userId: user._id, 
        author: user.emails[0].address, 
        created: moment().toDate()
    };

    console.log(item.date)

    var nameId = Meals.insert(item);
    var meal = Meals.findOne(nameId);
    console.log(meal)

console.log(item.date) 返回

Fri Nov 06 2015 00:00:00 GMT-0500 (Eastern Standard Time)

console.log(meal) 返回

_id: "vyrXkmRFsD5px7wFz"
author: "ellis.cs@gmail.com"
created: Sun Oct 25 2015 21:02:26 GMT-0400 (Eastern Daylight Time)
date: Fri Nov 06 2015 00:00:00 GMT-0500 (Eastern Standard Time)
name: "Tacos"
userId: "kyd9dMb9iCuRJTMhW"

但是,如果我立即做一个

Meals.find({name : "Tacos}).fetch();

返回

_id: "vyrXkmRFsD5px7wFz"
author: "ellis.cs@gmail.com"
created: Sun Oct 25 2015 21:02:25 GMT-0400 (Eastern Daylight Time)
date: Thu Nov 05 2015 19:00:00 GMT-0500 (Eastern Standard Time)
name: "Tacos"
userId: "kyd9dMb9iCuRJTMhW"

注意日期字段的差异。我在这里不知所措。

【问题讨论】:

    标签: javascript date meteor momentjs


    【解决方案1】:

    有2个注释:

    1. moment().utc().toDate():实际上返回 MomentJs 本身使用的本机 Date 对象,这是一个本地日期时间。可以通过以下代码查看:

      var now = moment().utc(); var localDateTime = 现在 .toDate(); var utcDateTime= now.toString(); 控制台.log(localDateTime); 控制台.log(utcDateTime);
    2. MongoDB 使用的 BSON Date 数据类型只是自 1970 年 1 月 1 日 UTC 以来的毫秒数的 64 位整数计数。因此,存储的实际值是 UTC 值。但是当你在浏览器控制台打印它时,它又回到了本地日期时间

    【讨论】:

    • 使用 toString() 解决了日期变化的问题,但是如果我将 Meteor 保存为字符串,我将失去按日期过滤的能力。我的发布依赖于仅显示特定范围内的日期。
    猜你喜欢
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    相关资源
    最近更新 更多