Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change date timezone in mongoose?

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?

like image 597
Aras Serdaroğlu Avatar asked Feb 27 '16 16:02

Aras Serdaroğlu


People also ask

How to set date in mongoose?

Here's how you declare a path of type Date with a Mongoose schema: const mongoose = require('mongoose'); const userSchema = new mongoose. Schema({ name: String, // `lastActiveAt` is a date lastActiveAt: Date }); const User = mongoose. model('User', userSchema);

How to add date type in mongoose schema?

var mySchema = new mongoose. Schema( {name: String}, {timestamps: true} ); This option adds createdAt and updatedAt properties that are timestamped with a Date , and which does all the work for you.

How do I set moment time zone?

To change the default time zone, use moment. tz. setDefault with a valid time zone.

How to store time in mongoose?

You can set the timestamps property to true when defining a Schema and mongoose will add a createdAt and updatedAt field for you. Mongoose will also update the updatedAt field for you when you do any update operation.


1 Answers

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.

like image 122
bamossza Avatar answered Sep 27 '22 01:09

bamossza