Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime difference in days on the basis of Date only

Tags:

c#

.net

c#-4.0

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:

  1. (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...
  2. dt1.day - dt2.day does not work across months
  3. dt.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.

like image 633
StartingFromScratch Avatar asked Sep 11 '25 06:09

StartingFromScratch


2 Answers

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
like image 191
Damien_The_Unbeliever Avatar answered Sep 12 '25 21:09

Damien_The_Unbeliever


If you use the DateTime.Date property this will eliminate the time

date1.Date.Subtract(date2.Date).Days
like image 31
Amiram Korach Avatar answered Sep 12 '25 21:09

Amiram Korach