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.
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.Instancedirectly in your code, it’s preferable that you inject anIClockdependency in your time-aware classes.This will allow you to:
SystemClock.Instanceat runtime, so the code will use the correct timeIClockduring 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.Nowreturn the current time would make it easier to hardcode usages ofSystemClockunder 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.Ticksrepresents the number of ticks since1/1/0001, and NodaTime’sInstant.Ticksrepresents the number of ticks since1/1/1970(see the remark here).