chaliasos
chaliasos

Reputation: 9793

Previous date is inserted on mongodb

I have a class with a DateTime field.

Class aClass 
{
    [BsonId]
    public int Id { get; set; }

    [BsonElement("dateCreated")]
    public DateTime DateCreated { get; set; }
}

But when I insert an bject in mongo via c# driver with a date let's say DateCreated = new DateTime(2013, 12, 08) the previous date is inserted.

> db.col.find();
{
    "_id" : 1,
    "dateCreated" :  ISODate("2013-12-07T22:00:00Z")
}

I am using MongoDb 2.2.6.

Upvotes: 2

Views: 687

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

MongoDB stores all DateTime values as UTC time (BSON Date type is the UTC datetime). That's why you see UTC time in database (your local time zone has two hours offset to UTC time). If you'll save UTC time, it will be stored as is. Check:

DateCreated = new DateTime(2013, 12, 8, 0, 0, 0, DateTimeKind.Utc)

When you are reading this values from database, they also will be have UTC time (value will be 12/7/2013 22:00:00 and if you'll check Kind property of date, it will be Utc). But you can ask Mongo to deserialize date into your local time zone date by applying BsonDateTimeOptions attribute:

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

Now same date will be deserialized as Local and it will have value 12/8/2013 00:00:00. You can enable same behavior to all DateTime values deserialization by setting default serialization options:

DateTimeSerializationOptions.Defaults = 
   DateTimeSerializationOptions.LocalInstance;

Upvotes: 1

Related Questions