Greg Veres
Greg Veres

Reputation: 1900

How to get number of days between two dates in nodatime

I need to compute the number of days between two dates using NodaTime, and to do it in a timezone.

The end time is date based with an implied time of midnight at the end of the day. This date is in a timezone.

The start time is the current time, but I am passing it into the function so that the function is testable.

I tried using Period, which seems like the obvious answer, but Period is too granular on one end (when we are on the end day) and not granular enough when we are more than 1 month away.

So if Now is July 9, 5:45pm in America/Toronto and the End Time is Sept 1, 00:00:00, then I would like to be able to calculate 54 days. (assuming I counted the number of days on my calendar correctly. :) )

I figured I would have to handle the sub day problem myself, but it surprised me when I had to figure out how to handle the greater than a month problem.

Is there an obvious way to get the number of days between two times from NodaTime? I have it down to three lines of code using .Net's DateTime and TimezoneInfo classes, but I want to move to NodaTime for all the reasons specified on the site.

Thanks

Upvotes: 14

Views: 4208

Answers (2)

mcont
mcont

Reputation: 1922

Starting with NodaTime 3.1 you can also use:

int days = Period.DaysBetween(startDate, endDate);

Where both parameters are LocalDates. Internally, this is simply implemented as endDate.DaysSinceEpoch - startDate.DaysSinceEpoch, after a calendar check.

Upvotes: 0

Greg Veres
Greg Veres

Reputation: 1900

I should have read the Arithmetic section of the docs more closely before posting.

You can specify which unit you want the math result to be in with a 3rd parameter. Here is what I needed:

Period timeLeft = Period.Between(nowInTz.LocalDateTime, endDate, PeriodUnits.Days);

this is from the docs: http://nodatime.org/unstable/userguide/arithmetic.html

Hope this helps somebody else in the future.

Upvotes: 22

Related Questions