I'm trying to get a handle on using the Noda Time framework by Jon Skeet (and others).
I'm trying to store the current now(Instant). Instant is created from a long ticks, but what is the current now count of Ticks?
Is it:
Instant now = new Instant(DateTime.Now.ToUniversalTime().Ticks);
And or?
Instant now = Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime());
Are they equivalent, am I even doing this right?
PS, if Jon answer's this - I'd like to propose an Instant.Now property.
PS2 I know the title contains a tag, but it wouldn't let me have a short "Instant.Now" title.
SystemClock.Now
returns the current time as anInstant
value:But you may want to heed the remarks in the documentation for the
IClock
interface:As a simple example, suppose you have a
Logger
class that needs the current time. Instead of accessingSystemClock
directly, use anIClock
instance that's supplied via its constructor:When you instantiate a
Logger
in your production code, you can give itSystemClock.Instance
. But in a unit test for theLogger
class, you can give it aFakeClock
.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 anIClock
dependency in your time-aware classes.This will allow you to:
SystemClock.Instance
at runtime, so the code will use the correct timeIClock
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()
orInstant.Now
return the current time would make it easier to hardcode usages ofSystemClock
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).