Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a NodaTime LocalDate representing "today"

Tags:

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?

like image 688
Redbaran Avatar asked Jan 09 '15 03:01

Redbaran


1 Answers

First recognize that when you say "today", the answer could be different for different people in different parts of the world. Therefore, in order to get the current local date, you must have a time zone in mind.

Noda Time correctly models this by giving you an Instant when you call Now from an IClock implementation such as the system clock. An instant is universal, so you just need to convert it to some time zone to get that time zone's local date.

// get the current time from the system clock Instant now = SystemClock.Instance.Now;  // get a time zone DateTimeZone tz = DateTimeZoneProviders.Tzdb["Asia/Tokyo"];  // use now and tz to get "today" LocalDate today = now.InZone(tz).Date; 

That's the minimal code. Of course, if you want to use the computer's local time zone (like you did with DateTime.Now), you can get it like so:

DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault(); 

And to really implement it properly, you should call .Now from the IClock interface, such that you could substitute the system clock with a fake clock for your unit tests.

This is a great example of how Noda Time intentionally doesn't hide things from you. All this is still going on under the hood when you call DateTime.Now, but you just don't see it. You can read more about Noda Time's design philosophy in the user guide.

like image 191
Matt Johnson-Pint Avatar answered Sep 20 '22 11:09

Matt Johnson-Pint