首页 > 解决方案 > 如何使用 UTC datetime 和 mongodb c# driver 比较两个 datetimeoffset

问题描述

我正在尝试使用 mongodb c# 驱动程序将 2 个 datetimeoffset 与 2 个不同的时区进行比较。我正在使用 datetimeoffset 的文档序列化来创建一个对象,该对象包括: - UTC 中的日期时间 - LOCAL 中的刻度 - 偏移量

我只想比较对象的日期时间部分,因为“2019-05-03 10:00:00 +01”等于“2019-05-03 09:00:00 +00”。

谢谢

标签: c#mongodbserializationdatetimeoffset

解决方案


有很多方法可以比较DateTimeOffset。这些方法比较 UTC 值DateTimeOffset

比较返回一个 int:

var c = DateTimeOffset.Compare(dto1, dto2);
// c > 0: dto1 is later
// c < 0: dto2 is later
// c == 0: dto1 and dto2 are the same in UTC

CompareTo类似于 compare(不同的语法),返回一个 int:

var c = dto1.CompareTo(dto2);
// c > 0: dto1 is later
// c < 0: dto2 is later
// c == 0: dto1 and dto2 are the same in UTC

等于返回布尔值:

var c = dto1.Equals(dto2);
// True: dto1 and dto2 have the same value in UTC
// False: dto1 and dto2 do not have the same UTC value

EqualsExact比较偏移量和时间,并返回一个布尔值:

var c = dto1.EqualsExact(dto2);
// True: dto1 and dto2 have the same value in UTC AND the same Offset
// False: dto1 and dto2 do not have the same UTC value or do not have the same Offset

看到这个小提琴


推荐阅读