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));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: