how to change date timezone in mongoose?
Asked Answered
T

9

18

In model schema,

Using

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

In 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);
        });

    });
});

However,

In db side it shows,

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

But, my timezone is UTC+02.00

So it should be like 18:20:42

What I'm doing wrong?

Tungstate answered 27/2, 2016 at 16:27 Comment(0)
R
12

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

enter image description here

:) Work for me.

Richia answered 20/8, 2018 at 9:52 Comment(1)
when you query dates, do you still get the dates in the timezone that you specified or mongodb returns dates in UTC formatFoumart
E
7

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.

Eduardo answered 27/2, 2016 at 16:49 Comment(2)
my ubuntu server timezone is EET so do I need to change it to UTC+2?Wanderoo
Best practice would be to keep your server's timezone to UTC, so that you do not get frustrated over datetime difference queries. Date-time will be much easier to reason about when in UTC. I've done it a lot of times and it saves you from a lot of time zone conversion headaches.Eduardo
S
7

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)

Sphygmograph answered 4/7, 2016 at 10:4 Comment(1)
So, how can I solve this ? Console.log is giving correct time but after insertion different time is shown their !Scholasticism
T
3

I changed this,

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

Now it works.

Tungstate answered 27/2, 2016 at 17:5 Comment(0)
A
2

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

new Date(Date.UTC(year, month, day, hour, minute, second))
Agency answered 27/2, 2016 at 16:52 Comment(0)
W
2

Remember that no matter what you use to set time in mongoose schema, mongoose will always use UTC time, hence you need to dynamically allocate the UTC timestamp inside the Schema. Here it goes :-

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 }
})
Winnick answered 14/7, 2021 at 18:54 Comment(1)
Worked like a charm. No need to install anything else too. Thanks!Christinachristine
O
1

Using moment.js it is as easy as:

var moment = require('moment');

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

Enjoy!

Obvolute answered 30/12, 2016 at 22:32 Comment(0)
M
0

Easiest way to do this for IST:

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 
})
Madisonmadlen answered 1/8, 2023 at 11:12 Comment(0)
U
0

It's quite simple I have found another way to fix this problem doesn't matter UTC just add two line in mongoose...

const time = new Date();
const currentDate =
time.toLocaleDateString() + " " + time.toLocaleTimeString();

And during post request just send this currentDate in schema and it will save time as your region

Unpromising answered 1/10, 2023 at 18:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.