Wrong time on Mongodb

Asked

Viewed 2,465 times

5

When I put in the schema mongodb:

created: { type: Date, default: Date.now }

The time is with a difference of 3 hours more.

How can I fix this?

2 answers

6


The MongoDB works with UTC, ie, time zone without adjustments. You will always have to consider this when using Date.

As in Brazil the time zones are -3h and -4h you will always see the hours more than your current.

Unfortunately there is no real way to fix this display within the MongoDB :(, but if you think on the other hand this is also good because it means that you can have many applications in several time zones and all of them can work from a fixed date (UTC).

1

As for reading, use Timezone after the date. e.g. Brazil GMT-3:00 is -300:

{
        $project: {
            "iso_date_field": 1,
            "hour": { $hour: { date: "$iso_date_field", timezone: "-0300" } },
            "hour2": { $hour: { date: ISODate("2020-08-14T02:08:04.000-03:00"), timezone: "-0300" } },
            "hour3": { $hour: { date: new Date(), timezone: "-0300" } }
        }
}

I can’t tell you about the recording, but I think you should go through the date normally...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.