Search code examples
c#mongodbasp.net-coremongodb-.net-driver

BsonDateTimeOptions doesn't set local datetime


Although I decorated my Datetime property with BsonDateTimeOptions , it still does not work and time inserted to database, 3 hours behind my local time.(I think it is utc)
My base abstract class

public abstract class MongoBaseModel
{
    public ObjectId Id { get; set; }

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

My Entity

public class RockSongs:MongoBaseModel
{
    [BsonElement("Name")]
    public string Name { get; set; }

    [BsonElement("Singer")]
    public string Singer { get; set; }
}

Db version v4.2.1

MongoDb.Driver 2.7.2


Solution

  • As per documentation:

    MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.

    There is no difference between DateTimeKind.Local and DateTimeKind.Utc when it comes to serialization. In both cases your .NET DateTime will be stored as UTC. The moment when this attribute becomes useful is deserialization. MongoDB .NET driver will automatically convert your UTC date time into your local computer's timezone if you apply DateTimeKind.Local.

    The fact that MongoDB stores dates as UTC comes directly from BSON specification.