gpt4 book ai didi

c# - NodaTime 的 Instant.Now

转载 作者:IT王子 更新时间:2023-10-29 04:21:06 29 4
gpt4 key购买 nike

我正在尝试使用 Noda Time Jon Skeet(和其他人)的框架。

我现在正在尝试存储当前(即时)。 Instant 是由一个长的 ticks 创建的,但是当前的 Ticks 数是多少?

是吗:

Instant now = new Instant(DateTime.Now.ToUniversalTime().Ticks);

和还是?

Instant now = Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime());

它们是等价的吗,我这样做对吗?

PS,如果 Jon 的回答是这个 - 我想提议一个 Instant.Now 属性。

PS2 我知道标题包含标签,但它不会让我有一个简短的“Instant.Now”标题。

最佳答案

我做了一些研究,NodaTime 的方法似乎是根据 clock 获取现在时刻.

如果您想使用系统时钟获取当前时间,只需使用 SystemClock.Instance.GetCurrentInstant()

但是,与其在代码中直接使用 SystemClock.Instance,不如在时间感知类中注入(inject) IClock 依赖项。

这将使您能够:

  • 在运行时为类提供 SystemClock.Instance,因此代码将使用正确的时间
  • 在单元测试期间提供 IClock 的假实现,以允许您根据需要调整时间以测试各种场景(如时间的流逝)。有一个 NodaTime.Testing 项目提供了这样一个类,称为 FakeClock

我觉得这很有用。我认为像 new Instant()Instant.Now 这样的东西返回当前时间会更容易在幕后对 SystemClock 的使用进行硬编码,因此缺少 NodaTime 提供的测试优势。

有关使用 NodaTime 进行单元测试的更多信息,请参阅 this link .


关于您的代码示例:它们不等同。

  • Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime()) 确实会以 UTC 格式为您提供当前时刻。
  • new Instant(DateTime.Now.ToUniversalTime().Ticks) 会给你一个遥远 future 的错误日期,因为 BCL 的 DateTime.Ticks表示自 1/1/0001 以来的刻度数,NodaTime 的 Instant.Ticks表示自 1/1/1970 以来的刻度数(请参阅备注 here)。

关于c# - NodaTime 的 Instant.Now,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14531627/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com