Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of days between two dates in nodatime

Tags:

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

like image 341
Greg Veres Avatar asked Jul 09 '16 21:07

Greg Veres


1 Answers

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.

like image 88
Greg Veres Avatar answered Oct 31 '22 08:10

Greg Veres