Pierre Greborio.NET

Talking about .NET world

Get the number of days between two DateTimes

Calculate the number of days between two dates seems really simple, but there are some exceptions. The simplest idea is to substract two DateTime and get the number of days in the resulting TimeSpan. The method doesn't work when the two dates are set with different year or the number of hour are less than 24 (consider 1/7/2005 10:00PM and 1/8/2005 8:00AM).

The solution (in this case applicable to Gregorian calendar) implies to define a date reference (ie. 3/1/1600) and calculates the astronomical day number:

int Days(DateTime time)
{
  int d = time.Day;
  int m = time.Month;
  int y = time.Year;

  if ((m -= 2) <= 0)
  {
    m += 12;
    y--;
  }

  y -= 1600;
  int cy = y / 100;
  return 365 * y + y / 4 - cy + cy / 4 + 367 * m / 12 + d - 31;
}

Finally, the number of days between two dates is given by the difference of their astronomical days number. The above formula has been attribued to Gauss.

Comments

Mario said:

good catch man!
# January 6, 2005 5:42 PM

Alejandro Perez said:

Have your try TotalDays property in the TimeSpan. It is a double but it can be easily rounded.
# January 6, 2005 6:14 PM

Pierre Greborio said:

Yes Alejandro, I did it and it doesn't work.
# January 6, 2005 6:19 PM

Deepak said:

What should the difference be?
When I execute this code, I get the difference of 0. Isn't this what you are expecting?

DateTime date1 = DateTime.Parse("10/01/2004 10:00PM");
DateTime date2 = DateTime.Parse("10/01/2004 09:50PM");
TimeSpan ts = date1.Subtract(date2);

Console.WriteLine(ts.Days.ToString());
# January 9, 2005 6:20 PM

RADHIKA said:

Get the number of days between two DateTimes IN c#

# August 3, 2007 2:39 AM