Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime issues with Mongo and C#

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?

like image 998
Micah Avatar asked May 17 '11 20:05

Micah


2 Answers

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.

like image 89
Robert Stam Avatar answered Nov 07 '22 23:11

Robert Stam


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;
    }
}
like image 30
Bala R Avatar answered Nov 08 '22 00:11

Bala R