使用nodatime如何找到两个ZonedDateTime对象之间的差异

时间:2015-10-30 13:20:14

标签: c# datetime timezone nodatime

使用nodatime如何在ZonedDateTime时区中找到两个ZonedDateTime对象之间的区别。

编辑 - 示例:

例如,我在时区中有两个日期,让我们使用“欧洲/斯德哥尔摩”时间。

这些是在本地时间设置为“America / Los_Angeles”的服务器上计算的。

我希望在“欧洲/斯德哥尔摩”时区获得两个时段之间的毫秒数,而忽略服务器的本地时间。这是因为如果部署到不同的服务器,服务器本地时间可能会发生变化,如果发生这种情况,我不希望更新代码。

2 个答案:

答案 0 :(得分:5)

试试这个:

ZonedDateTime t1 = LocalDateTime.FromDateTime(startTime).InUtc();
ZonedDateTime t2 = LocalDateTime.FromDateTime(endTime).InUtc();
Duration diff = t2.ToInstant() - t1.ToInstant();

答案 1 :(得分:0)

"Between two periods" doesn't make much sense, as a ZonedDateTime isn't a period. If you have two ZonedDateTime values, you probably just need to call ToInstant on both of them, then subtract one instant from the other to get the duration..."

This comment from Jon Skeet answers the question, Calling ToInstant allows you to use the subtract [-] and add [+] operators.