manish singh
manish singh

Reputation: 97

Mongodb and Node.js datetime timezone issue

I am having hard time to understand the concept of querying date in mongodb/node.js, even after going through many SO and other articles in google.

While storing the date from a react datepicker  in mongodb it gets stored a day less as per my time zone but when it is fetched it is shown the same,I can understand that it is again being converted into locale

but how do query responds?

When I query  mongodb from node.js/mongoose - I don't find the correct resultSo my question is while querying the mongodb - how dates are passed to mongodb ? for example :

post.find({publish_date:{ $gte:new Date()}}

What is the new Date value - localtime zone of the server? or  browser?

is the new date value converted to utc while comparing the database or compared as passed from the server ?

I have a post model where I want the post to be published on the published_date as per my timezone.

for example - if I put 2021-01-21 mongo stores 2021-01-20T18:30:00.000+00:00 - it is understood that it stored as UTC

Now when I am querying the post to be published when the server date/time is 2021-01-21 - it is not fetch any document!

When I change the publish_date as 2021-01-22 mongo stores 2021-01-21T18:30:00.000+00:00 then query produces on document.

I am not sure how to solve this problem

Any help in this regard would be helpful

Thanks.

Upvotes: 1

Views: 1944

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59436

In MongoDB all Date values are stored as UTC-Times only.

Your client application is responsible to display these UTC times as local times, if required.

MongoDB does not preserve the input time zone, if you need this for any reason then you have to store it in a separate field.

In Mongo you can display locals date/times values with $dateToString:

{ $dateToString: {
    date: <dateExpression>,
    format: <formatString>,
    timezone: <tzExpression>,
    onNull: <expression>
} }

Whenever one has to work with date/time values then I recommend the moment.js library.

The query could be this for example:

{ $gte: moment().startOf('day').toDate() }

I am in Switzerland where we have UTC+01:00, thus moment().startOf('day').toDate() returns ISODate("2021-01-20T23:00:00Z")

Upvotes: 1

Related Questions