-->

Correct insert DateTime from c# to mongodb

2020-02-24 01:32发布

问题:

I try to insert local time in MongoDB

var time = DateTime.Now; // 03.05.2014 18:30:30

var query = new QueryDocument
{
   { "time", nowTime}
};

collection3.Insert(query);

But in database I see ISODate("2014-05-03T15:30:30.170Z"),
that must be ISODate("2014-05-03T18:30:30.300Z").
Please help me!

回答1:

I think you're getting confused by time zones. The Z at the end of the string indicates that it's in UTC. When you posted this question, it was just after 15:30 UTC.

I strongly suspect that the correct instant in time is being recorded - but it's being recorded as an instant in time without reference to a particular time zone. You can then convert that to whatever time zone you want later on, but recording the UTC time is almost always the correct approach.

As an aside, you can make this clearer by using UtcNow to start with. That way it's more obvious that you're not trying to obtain a "local" time.

Looking at the MongoDB documentation, it seems that the internal representation is simply a number of milliseconds since the Unix epoch - so again, that has no indication of time zone or an offset between UTC and local time. If you want to store a value which can be converted back to the local time you saw when it was recorded (even if you're now in a different time zone) you should store a time zone ID and/or the UTC offset as a separate value. That's not needed terribly often, but it's an option.



回答2:

The MongoDB driver is converting your DateTime to UTC.

If you don't want to bother with time zones, you could change the kind to UTC:

time = DateTime.SpecifyKind(time, DateTimeKind.Utc);

I would not recommed this because the database will store a "wrong" Date, but it will show you ISODate("2014-05-03T18:30:30.170Z").



回答3:

Just define the "Kind" of the DateTime by the "BsonDateTimeOptions" attribute and set it to local:

[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime SomeDateProperty {get;set;}


回答4:

It could work with:

    DateTime t = DateTime.Now;

    var update = Builders<BsonDocument>.Update
    .Set("key1", t.ToUniversalTime())
    .CurrentDate("key_updatetime");