I need to find the difference in days between two dates.
For example:
Input: **startDate** = 12-31-2012 23hr:59mn:00sec, **endDate** = 01-01-2013 00hr:15mn:00sec
Expected output: 1
I tried the following:
(dt1-dt2).TotalDays
and convert to integer but didn't give me appropriate answer as double has to be converted to int - tried Math.Ceiling, Convert.To...dt1.day - dt2.day
does not work across monthsdt.Substract()
has the same output as option 1 mentioned above.None of the above worked, so I ended up writing the following code. The code works well, but I feel that there must be a solution with only a couple of lines of code.
public static int GetDifferenceInDaysX(this DateTime startDate, DateTime endDate)
{
//Initializing with 0 as default return value
int difference = 0;
//If either of the dates are not set then return 0 instead of throwing an exception
if (startDate == default(DateTime) | endDate == default(DateTime))
return difference;
//If the dates are same then return 0
if (startDate.ToShortDateString() == endDate.ToShortDateString())
return difference;
//startDate moving towards endDate either with increment or decrement
while (startDate.AddDays(difference).ToShortDateString() != endDate.ToShortDateString())
{
difference = (startDate < endDate) ? ++difference : --difference;
}
return difference;
}
Note: I do not have any performance issue in the while-loop iteration as the max difference will not be more than 30 to 45 days.
Well, it sounds like you want the difference in the number of days, ignoring the time component. A DateTime
with the time component reset to 00:00:00 is what the Date
property gives you:
(startDate.Date - endDate.Date).TotalDays
If you use the DateTime.Date
property this will eliminate the time
date1.Date.Subtract(date2.Date).Days
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With