I am new to Noda Time
and I basically want to compare if a date has expired or not. In my case I have an object with the date
it was created, represented by a LocalDate
and the amount of months
it's valid as an int
, so I wanted to do a simple:
if ( Now > (dateCreated + validMonths) ) expired = true;
But I can't find in the Noda Time documentation the proper way to get the Now Date (they only show how to get the Now Time as SystemClock.Instance.Now
) and the proper way to handle time comparisons.
For example if today is January 1st 2015 and the document was created in December 1st 2014, and it was valid for one month, today it expires its one month validity.
I miss methods such as isBefore()
and isAfter()
to compare dates and times. Simple overloads of the < > operators could also be very helpful.
EDIT:
1 - Sorry, there are <
>
operators to compare dates.
2 - I solve my problem using this code (not tested yet!):
...
LocalDate dateNow = this.clock.Now.InZone(DateTimeZoneProviders.Tzdb.GetSystemDefault()).LocalDateTime.Date;
LocalDate dateExpiration = DataASO.PlusMonths(validity);
return (dateNow < dateExpiration);
To get the current date, you need to specify which time zone you're in. So given a clock and a time zone, you'd use:
LocalDate today = clock.Now.InZone(zone).Date;
While you can use SystemClock.Instance
, it's generally better to inject an IClock
into your code, so you can test it easily.
Note that in Noda Time 2.0 this will be simpler, using ZonedClock
, where it will just be:
LocalDate today = zonedClock.GetCurrentDate();
... but of course you'll need to create a ZonedClock
by combining an IClock
and a DateTimeZone
. The fundamentals are still the same, it's just a bit more convenient if you're using the same zone in multiple places. For example:
// These are IClock extension methods...
ZonedClock zonedClock = SystemClock.Instance.InTzdbSystemDefaultZone();
// Or...
ZonedClock zonedClock = SystemClock.Instance.InZone(specificZone);
See more on this question at Stackoverflow