Yurii Hohan
Yurii Hohan

Reputation: 4171

IsoDate and DateTime in MongoDB using C#

Let us suppose that I want to query mongo on the dateTime. I have two C# variables representing the start and the end date.

1) {20.10.2011 00:00:00}

2) {22.10.2011 00:00:00}

Now the BsonDateTime.Create(dateTime) transformed them to a BSON DateTime well too:

1) 2011-10-20T00:00:00 MongoDB.Bson.BsonDateTime

2) 2011-10-22T00:00:00 MongoDB.Bson.BsonDateTime

This is the code creating the dateTimes(_value is a string):

DateTime dateTime;
bool parsed = DateTime.TryParse(_value, out dateTime);
if (!parsed)
    throw new FormatException("Wrong format for a query param");
return BsonDateTime.Create(dateTime);

Then the next code builds the query:

private QueryComplete MakeQuery(string key, BsonValue value)
{
    if (_separatorType == ">=")
        return Query.GTE(key, value);
    if (_separatorType == "<=")
        return Query.LTE(key, value);
    return Query.EQ(key, value);
}

And i do get such a strange value in a query:

"Sessions.End" : { "$gte" : ISODate("2011-10-19T21:00:00Z"), "$lte" : ISODate("2011-10-21T21:00:00Z") },

Well, I google ISODate but haven't found any reason why it should be shifted. Is it OK?

Upvotes: 12

Views: 15599

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499740

I believe the problem is that DateTime.TryParse is giving you a DateTime with a Kind of Local... whereas the ISO date is always in UTC. I expect that some part of the MongoDB code is converting the local DateTime to one in UTC. It's largely not your fault - basically, DateTime is a very confusing type.

I suspect if you specify DateTimeStyles.AssumeUniversal in your parsing code, it will do what you expect.

(Shameless plug: my own project, Noda Time, makes all of this a lot simpler...)

Upvotes: 16

Related Questions