NodeJS 如何在 Mongoose 中更改日期时区?

lndjwyie  于 2023-08-04  发布在  Node.js
关注(0)|答案(8)|浏览(94)

在模型模式中,
正在使用

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
我做错了什么?

sxpgvts3

sxpgvts31#

我用的是moment-timezone

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

字符串
Mongoose 中的图式。

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 }了吗

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

Options > Display Dates In... > Local Timezone


x1c 0d1x的数据
为我工作。

ahy6op9u

ahy6op9u2#

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

7z5jn7bk

7z5jn7bk3#

你的代码没有任何错误。MongoDb以UTC格式保存日期,无论您尝试在哪个时区插入日期。
如果您在保存到数据库之前记录domain.updated,结果将是UTC+2(您的本地时间)
如果您在DB中看到更新的列,则结果将以UTC表示
如果你从数据库中获取更新的列值,那么结果将再次以UTC+2(你的本地时间)表示

ztigrdn8

ztigrdn84#

我改了这个,

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

字符串
现在起作用了

bksxznpy

bksxznpy5#

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

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

字符串

mrfwxfqh

mrfwxfqh6#

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

var current = new Date();
const timeStamp = new Date(Date.UTC(current.getFullYear(), 
current.getMonth(),current.getDate(),current.getHours(), 
current.getMinutes(),current.getSeconds(), current.getMilliseconds()));

//Here goes your schema 
const auditSchema = mongoose.Schema({
           dateTime : { type: Date, default : timeStamp }
})

字符串

62o28rlo

62o28rlo7#

使用moment.js很简单:

var moment = require('moment');

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

字符串
好好享受吧!

pgvzfuti

pgvzfuti8#

  • 最简单的方法来做到这一点:
`const companySchema = new Schema({
    name : { type: String, default : "" },
    email : { type: String, default : "" }
},
{ 
    timestamps: { currentTime: () => {
        let date = new Date();
        let newDate = new Date(date.getTime() + (date.getTimezoneOffset() * 60 * 1000 * -1));
        return newDate;
    }},  
    versionKey: false 
})`

字符串

相关问题