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?
MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed.
new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
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.
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”.
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With