Mongo – DateTime Issue

There is an issue with Mongo DB (it is an issue if you don’t need that feature). Whenever you pass a date in an entity to a Mongo DB server in a different timezone it will automatically adjust the DateTime value of the object property.

The problem is very easy to solve by decorating the DateTime property with

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

where you do need the time component or

[BsonDateTimeOptions(DateOnly = true)]
public DateTime ReportingDate { get; set; }

when you only care about the date.

An even better solution is to set a global setting of the C# driver:

BsonSerializer.RegisterSerializer(typeof(DateTime), new DateTimeSerializer(DateTimeSerializationOption(DateTimeSerializationOptions.LocalInstance));

Blog at WordPress.com.

Up ↑