与蒙戈和C#日期时间问题日期、时间、问题

2023-09-09 21:05:39 作者:春风十里不如你

我在使用保存和使用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.

在我店这样的:

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?

推荐答案

的原因是,BSON日期时间格式存储值少precision比.NET DateTime值,所以当你从数据库中读取回来了值已被截断。

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.

如果你的DateTime值是要序列化,你可以问序列化的日期时间值,同时包含BSON日期时间值(截断)和原始.NET DateTime值嵌入文档序列化一个C#类的属性(如存储蜱)。在这种情况下,反序列化时的值不会被截断。

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.

例如:

public class MyClass {
    public ObjectId Id;
    [BsonRepresentation(BsonType.Document)]
    public DateTime MyDateTime;
}

您还可以使用的Int64或字符串的BsonRe presentation,而不是失去precision,但随后的存储文件的只有的有蜱或字符串再presentation无BSON日期时间,这使得它很难做到的日期时间相关的查询。

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.

你还需要记住的日期时间值存储在UTC在数据库中。最好的做法是始终使用UTC值存储其中仅显示给用户时,使用本地时间。

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.