简体   繁体   English

Mongo和C#的日期时间问题

[英]Datetime issues with Mongo and C#

I'm having an issue with saving and retrieving dates with Mongo using the c# driver. 我在使用c#驱动程序保存和检索Mongo的日期时遇到问题。 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. 原因是BSON DateTime格式存储的值的精度低于.NET DateTime值,因此当您从数据库中读取它时,该值已被截断。

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). 如果您的DateTime值是您正在序列化的C#类的属性,您可以要求序列化程序将DateTime值序列化为包含BSON DateTime值(截断)和原始.NET DateTime值(存储为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. 您还可以使用Int64或String的BsonRepresentation而不会丢失精度,但是存储的文档只有 Ticks或字符串表示而没有BSON DateTime,这使得很难进行与DateTime相关的查询。

You'll also want to keep in mind that DateTime values are stored in UTC in the database. 您还需要记住,DateTime值以UTC格式存储在数据库中。 The best practice is to always use UTC values for storage and only use local times when displaying them to the user. 最佳做法是始终使用UTC值进行存储,并仅在向用户显示时使用本地时间。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM