14

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

Greg Veres
  • 1,770
  • 19
  • 28

2 Answers2

21

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.

Greg Veres
  • 1,770
  • 19
  • 28
  • One thing to note, is that if you ask for Days and there is 1 partial day left you will get a period with all zeros. The other values, like hours wont be filled in. – Greg Veres Jul 09 '16 at 22:44
  • You could always ask for a period with time units + days, if the latter part is an issue for you. – Jon Skeet Jul 10 '16 at 09:01
  • Ah right I can or the PeriodUnits. That makes sense. Thanks. – Greg Veres Jul 10 '16 at 12:19
0

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.

mcont
  • 1,749
  • 1
  • 22
  • 33