how to change date timezone in mongoose?

前端 未结 6 1276
太阳男子
太阳男子 2021-01-04 11:38

In model schema,

Using

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

In server.js

put(function(req, res) {
    v         


        
相关标签:
6条回答
  • 2021-01-04 12:19

    The timestamps are timezone agnostic, stored as a unix timestamp. This timestamp will work across timezones, and node interprets it using current timezone of the server. The date you've shown is correctly stored. As soon as you'll retrieve it, if your server's timezone is UTC+2, it will show you correct time.

    0 讨论(0)
  • 2021-01-04 12:28

    I'm using 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
    

    Schema in the 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}
    );
    

    See up that created_date, updated_date: {type: Date, default: dateThailand }

    Read more: http://momentjs.com/timezone/docs/

    *If you using Robo 3T tool.

    You can set "Display Dates In..."

    Options > Display Dates In... > Local Timezone
    

    :) Work for me.

    0 讨论(0)
  • 2021-01-04 12:30

    Using moment.js it is as easy as:

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

    Enjoy!

    0 讨论(0)
  • 2021-01-04 12:40

    There is nothing wrong in your code. MongoDb saves date in UTC format no matter in whichever timezone you try to insert your date.

    If you log domain.updated before saving in DB, result will be UTC+2 (your local time)

    If you see updated column in DB, result will be in UTC

    If you fetch updated column value from DB, then again result will be in UTC+2 (your local time)

    0 讨论(0)
  • 2021-01-04 12:42

    I changed this,

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

    Now it works.

    0 讨论(0)
  • 2021-01-04 12:44

    You can create a Date Object from a specific UTC time:

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

    0 讨论(0)
提交回复
热议问题