What is the recommended way to create a LocalDate instance that represents "today". I was expecting there to be a static "Now" or "Today" property in the LocalDate class, but there isn't. My current approach is to use DateTime.Now:
var now = DateTime.Now;
LocalDate today = new LocalDate(now.Year, now.Month, now.Day);
Is there a better way?
Matt's answer is spot on for Noda Time 1.x.
In Noda Time 2.0, I'm introducing a ZonedClock
, which is basically a combination of IClock
and a DateTimeZone
. As you're likely to want the current time in the same time zone multiple times, you can inject that (I'm assuming you're using dependency injection) and retain that, then use it. For example:
class SomeClass
{
private readonly ZonedClock clock;
internal SomeClass(ZonedClock clock)
{
this.clock = clock;
}
internal void DoSomethingWithDate()
{
LocalDate today = clock.GetCurrentDate();
...
}
}
You would normally provide the ZonedClock
by taking an IClock
and using one of the new extension methods, e.g.
var clock = SystemClock.Instance;
var zoned = clock.InUtc();
// Or...
var zoned = clock.InZone(DateTimeZoneProviders.Tzdb["Europe/London"];
// Or...
var zoned = clock.InTzdbSystemDefaultZone();
// Or...
var zoned = clock.InBclSystemDefaultZone();
Note that your 1.x code won't work in 2.x anyway - I'm removing the Now
property from IClock
as it really shouldn't be a property (given the way it changes) - it's now a GetCurrentInstant()
method.;
See more on this question at Stackoverflow