Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 432
Yurii Hohan Avatar asked Oct 21 '11 09:10

Yurii Hohan


People also ask

How is datetime stored in MongoDB?

MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed.

What is the datetime format in MongoDB?

new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.

What is ISODate in MongoDB?

ISODate() is a helper function that's built into to MongoDB and wraps the native JavaScript Date object. When you use the ISODate() constructor from the Mongo shell, it actually returns a JavaScript Date object.

Can I store date as string in MongoDB?

MongoDB will treat them as they are - string data type. And, the string comparison rules will apply. You can safely store dates as strings and query on them as long as they are properly formatted for date, i.e., “YYYY-MM-ddTHH:mm:ss”.


1 Answers

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

like image 113
Jon Skeet Avatar answered Oct 15 '22 08:10

Jon Skeet