如何在mongoose中更改日期时区?

时间:2016-02-27 16:27:25

标签: node.js date express mongoose

在模型架构中,

使用

updated: {
    type: Date,
    default: Date.now

在server.js

put(function(req, res) {
    var query = {name: req.params.name};
    // use our bear model to find the bear we want
    Domain.find(query, function(err, domains) {

        if (err)
            res.send(err);
        var domain = domains[0];
        domain.password = req.body.password;  // update the bears info
        domain.updated = new Date();
        // save the bear
        domain.save(function(err, data) {
            if (err)
                res.send(err);

            res.json({ status: 'success', message: 'domain updated!' }, data);
        });

    });
});

然而,

在db方面显示,

"updated": "2016-02-27T16:20:42.941Z"

但是,我的时区是UTC + 02.00

所以它应该像18:20:42

我做错了什么?

8 个答案:

答案 0 :(得分:3)

时间戳与时区无关,存储为unix时间戳。此时间戳将跨时区工作,节点使用服务器的当前时区对其进行解释。您显示的日期已正确存储。一旦您检索到它,如果您的服务器的时区是UTC + 2,它将显示正确的时间。

答案 1 :(得分:2)

您的代码没有任何问题。无论您尝试插入日期的哪个时区,MongoDb都会以UTC格式保存日期。

如果您在保存到DB之前记录domain.updated,结果将是UTC + 2(您当地时间)

如果您在DB中看到更新的列,则结果将为UTC

如果您从DB获取更新的列值,那么结果将再次为UTC + 2(您当地时间)

答案 2 :(得分:2)

我使用的是时区

npm install moment-timezone

const moment = require('moment-timezone');
const dateThailand = moment.tz(Date.now(), "Asia/Bangkok");

console.log(dateThailand); // "2018-08-20T16:35:14.033+07:00"
*** Asia/Bangkok +07:00

猫鼬中的架构。

const categorySchema = new Schema(
    {
        _id: {type: mongoose.Schema.Types.ObjectId, auto: true},
        c_name: String,
        created_by: String,
        created_date: {type: Date, default: dateThailand},
        updated_by: String,
        updated_date: {type: Date, default: dateThailand}
    }, {_id: false}
);

查看created_date, updated_date: {type: Date, default: dateThailand }

了解详情: http://momentjs.com/timezone/docs/

*如果您使用的是Robo 3T工具。

您可以设置“显示日期在...”

Options > Display Dates In... > Local Timezone

enter image description here

:)为我工作。

答案 3 :(得分:1)

您可以从特定的UTC时间创建日期对象:

new Date(Date.UTC(year, month, day, hour, minute, second))

答案 4 :(得分:1)

使用moment.js就像:

一样简单
var moment = require('moment');

var utcDate = moment.utc().toDate();

享受!

答案 5 :(得分:0)

我改变了这个,

var utc = new Date();
utc.setHours( utc.getHours() + 2);
domain.updated = utc;

现在可行。

答案 6 :(得分:0)

我找到了一个解决方案:mongoose-timezone插件

请参阅here

有效!

答案 7 :(得分:0)

请记住,无论您在 mongoose schema 中使用什么设置时间,mongoose 都将始终使用 UTC 时间,因此您需要在 Schema 中动态分配 UTC 时间戳。在这里:-

err != nil