I'm having an issue with saving and retrieving dates with Mongo using the c# driver. For some reason it it's truncating the ticks.
When I store this:
DateTime -> 5/17/2011 7:59:13 PM
Ticks -> 634412591533741650
I get this back:
DateTime -> 5/17/2011 7:59:13 PM
Ticks -> 634412591533740000
So if I try to do:
serverDateTime == mongoDateTime
It always fails. Anyway around this?
The reason is that the BSON DateTime format stores values with less precision than a .NET DateTime value, so when you read it back from the database the value has been truncated.
If your DateTime value is a property of a C# class you are serializing you can ask the serializer to serialize the DateTime value as an embedded document containing both the BSON DateTime value (truncated) and the original .NET DateTime value (stored as Ticks). In that case the value will not be truncated when deserialized.
For example:
public class MyClass {
public ObjectId Id;
[BsonRepresentation(BsonType.Document)]
public DateTime MyDateTime;
}
You can also use a BsonRepresentation of Int64 or String and not lose precision, but then the stored document only has Ticks or a string representation and no BSON DateTime, which makes it hard to do DateTime related queries.
You'll also want to keep in mind that DateTime values are stored in UTC in the database. The best practice is to always use UTC values for storage and only use local times when displaying them to the user.
Here's an extension you could use :)
public static class MongoDateComparison
{
private static int precisionInMilliseconds = 1000;
public static bool MongoEquals(this DateTime dateTime, DateTime mongoDateTime)
{
return Math.Abs((dateTime - mongoDateTime).TotalMilliseconds) < precisionInMilliseconds;
}
}
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