About MongoDB Time zone issues

Source: Internet
Author: User
Tags local time mongodb

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:

    1. How to save date properly?
    2. What is the new setting datetimeserializationoptions.defaults in MongoDB C # driver?

About MongoDB Time zone issues

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.