I did a bit of research and it seems that the NodaTime way is to get the now moment according to a clock.
If you want to get the current time using the system clock, just use SystemClock.Instance.GetCurrentInstant()
.
However, instead of using the SystemClock.Instance
directly in your code, it's preferable that you inject an IClock
dependency in your time-aware classes.
This will allow you to:
- provide the class with
SystemClock.Instance
at runtime, so the code will use the correct time - supply a fake implementation of
IClock
during unit testing to allow you to tweak the time as needed in order to test various scenarios (like the passing of time). There's a NodaTime.Testing project that offers such a class, calledFakeClock
.
I find this very useful. I think having something like new Instant()
or Instant.Now
return the current time would make it easier to hardcode usages of SystemClock
under the covers, therefore missing the testing advantage that NodaTime offers.
For more info on unit testing with NodaTime, see this link.
Regarding your code examples: they are not equivalent.
Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime())
will indeed give you the current instant in UTC.new Instant(DateTime.Now.ToUniversalTime().Ticks)
will give you a wrong date far in the future, because the BCL'sDateTime.Ticks
represents the number of ticks since1/1/0001
, and NodaTime'sInstant.Ticks
represents the number of ticks since1/1/1970
(see the remark here).