如何在NodatTime中为Instant添加年份?

问题描述 投票:0回答:1

NodaTime 的文档 我明白为什么 ZonedDateTime 或 Instant 上没有 AddYear。然而,我需要某种方法来到达“明年的这个时间”(我需要的所有时间都以 UTC 存储/使用)。到目前为止,我想到的是:

        var start = SystemClock.Instance.GetCurrentInstant().InUtc();
        var nextyear = start.Date.PlusYears(1).At(start.TimeOfDay).InUtc().ToInstant();

这是正确的方法吗?在 ZonedDateTime 上没有 AddYear 的所有原因中,我可能会遇到问题吗?

c# nodatime
1个回答
0
投票

如果您处理UTC,并且您使用ISO(公历)日历,那么您所拥有的应该没问题,尽管它可以简化为:

var nextYear = SystemClock.Instance.GetCurrentInstant()
   .InUtc()
   .LocalDateTime
   .PlusYears(1)
   .InUtc()
   .ToInstant();

可以对 UTC 执行此操作的原因是 UTC 没有任何转换 - 您无需担心“从本地日期/时间起一年”不明确或被跳过。

值得一提的是,确切地您正在做什么 - 您正在向“UTC 中的当前公历日期/时间”添加一年,而不是向“当前即时时间”添加一年,因为Instant 没有“一年”的概念。

© www.soinside.com 2019 - 2024. All rights reserved.