B
B
Boniface2014-05-28 10:34:53
MongoDB
Boniface, 2014-05-28 10:34:53

How to store date in UTC in MongoDB (C# driver)?

Hello! Faced such a problem. Trying to store date in UTC in mongoDB. The date is already in utc (kind= utc), but when the date is saved to the database, it is converted to UTC again. That is, in mongoDB it has already been stored for (-8) hours!!!
For example. Current local date = 11/11/2014 11:30 AM. In UTC it will be 11/11/2014 7:30. So, when I save 11/11/2014 7:30 (kind = UTC) in mongoDB, the date is again converted to UTC, as a result, 11/11/2014 3:30 is already in mongoDB.
The problem can be solved by converting the date to local time or adding 4 hours before storing it in mongodb. But somehow it's really very clumsy. Tell me, how can I set up the base so that the date, which is already in utc, is not converted to utc again?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nesvet, 2014-05-28
@Nesvet

Store a string from Date.toJSON() as a date:

var now = new Date(); // текущая дата
var dateString = now.toJSON(); // строка с датой в UTC; удобно хранить в mongo
var parsedDate = new Date(dateString); // преобразовали строку обратно в объект

B
Boniface, 2014-05-30
@Boniface

Not not an option ... It's better to translate the date into the locale before saving. Then in monge the date will be GMT. All OK. But I thought there is some kind of trick in setting up the driver, serializer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question