Since the MongoDB storage time is stored in UTC time, its official drive mongodb.driver the time to save the local time to UTC time, but it has an egg-sore bug, and when read it is very painful to return UTC to make the time. A very intuitive embodiment is that the time Type field is stored and re-read into the inconsistency, a simple example is as follows:
Table. Insertone (new MyClass () { = DateTime.Now,}); foreach (varintrue). ToList ()) { Console.WriteLine (data. time);}
Running this code will find that the time to read out and write a difference of 8 hours (Beijing time).
itself MongoDB official is aware of this, there are many people reacting to this problem: DateTime timezone problem. , but the official is not modified by the intention, the official proposed modification method is: The time Type attribute field is explicitly labeled as local time
[Bsondatetimeoptions (Kind = datetimekind.local)] Public DateTime Somedateproperty {get; Set;}
Although this method seems to have no problem, it is cumbersome to use, one to introduce the Bson library in some unrelated DTO libraries, on the other hand, tagging is easy to omit. In fact, it is inconvenient to operate.
So, someone has found another way, that is, the way to set the global time serialization:
Datetimeserializationoptions.defaults = datetimeserializationoptions.localinstance;
This method is only valid in the Mongodb.driver 1.x version, after 2.x, Datetimeserializationoptions has been discarded, you can use the following methods:
var New Datetimeserializer (datetimekind.local, bsontype.datetime); Bsonserializer.registerserializer (typeof(DateTime), serializer);
Reference article:
- How to save date properly?
- What is the new setting datetimeserializationoptions.defaults in MongoDB C # driver?
About MongoDB Time zone issues