Mongo 和 C# 的日期时间问题
我在使用 c# 驱动程序使用 Mongo 保存和检索日期时遇到问题。由于某种原因,它会截断刻度线。
当我存储这个:
DateTime -> 5/17/2011 7:59:13 PM
Ticks -> 634412591533741650
我得到这个:
DateTime -> 5/17/2011 7:59:13 PM
Ticks -> 634412591533740000
所以如果我尝试这样做:
serverDateTime == mongoDateTime
它总是失败。无论如何?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
原因是 BSON DateTime 格式存储的值的精度低于 .NET DateTime 值,因此当您从数据库读回该值时,该值已被截断。
如果您的 DateTime 值是您要序列化的 C# 类的属性,您可以要求序列化程序将 DateTime 值序列化为嵌入文档,其中包含 BSON DateTime 值(截断)和原始 .NET DateTime 值(存储为 Ticks)。在这种情况下,反序列化时该值不会被截断。
例如:
您还可以使用 Int64 或 String 的 BsonRepresentation 并且不会丢失精度,但是存储的文档仅具有 Ticks 或字符串表示形式,而没有 BSON DateTime,这使得很难执行与 DateTime 相关的操作查询。
您还需要记住,DateTime 值在数据库中以 UTC 格式存储。最佳实践是始终使用 UTC 值进行存储,并且在向用户显示这些值时仅使用当地时间。
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:
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 :)