How to save date properly?
c# driver by default (without extra settings) saving local dates as utc date into database (date - time zone offset) but reading back without any action (so, utc date).
Because of this when you loading datetime from database you receive diff in 2 hours (your timezone offset). There are two approaches how to say to mongodb c# driver convert utc dates to local timezone dates during deserialization:
1.through the attributes for particular date field:
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime SomeDateProperty {get;set;}
2.through global settings for all datetime fields (default is UtcInstance
):
DateTimeSerializationOptions.Defaults = DateTimeSerializationOptions.LocalInstance;
Once you will do #1 or #2 you will see local date.
Update:
#2 is obsolete in latest driver version so use code below instead:
BsonSerializer.RegisterSerializer(typeof(DateTime),
new DateTimeSerializer(DateTimeSerializationOptions.LocalInstance));
Update:
#2 has changed again:
BsonSerializer.RegisterSerializer(typeof(DateTime), DateTimeSerializer.LocalInstance);
You're running into a timezone issue. Your date object is probably in a timezone other than UTC (2 hours ahead by the looks of it) or your default timezone is set to something other than UTC. The driver will convert the date to the appropriate timezone before storing it in the database.
Normally you wouldn't notice this since the reverse (retrieving the UTC date from the database) should convert it back to the original timezone. There might be an issue with the driver you're using or C# might require a bit more code to get it right.
Storing dates as strings is usually not a good idea since it disables range queries on dates.