Calculating the number of months and days between two dates using C# 19 June 2006 at 00:00

This function calculates the difference in months between two dates, returning the number of months and days between the two. This is actually a simplified version of the function written by Julian Bucknall - his more complex version worries about sticky month endings.

public static void DateDiffMonths(DateTime date1, DateTime date2, out int months, out int days) 
{

  // ensure that date1 <= date2
  if (date2 < date1) 
  {
    DateTime dtTemp = date2;
    date2 = date1;
    date1 = dtTemp;
  }
  
  // make a guess at the answer, using 31 means that we'll be close but won't exceed
  int monthCount = ((date2 - date1).Days / 31); 
  
  // find the maximum number of months that's less than or equal to the second date
  DateTime dateTest = date1.AddMonths(monthCount);
  while (dateTest < date2) 
  {
    dateTest = date1.AddMonths(++monthCount);
  }
  
  // if we've hit the exact date, return the number of months and zero days
  if (dateTest == date2) 
  {
    months = monthCount;
    days = 0;
    return;
  }
  
  // otherwise we exceeded the second date, back up and return the correct values
  dateTest = date1.AddMonths(--monthCount);
  months = monthCount;
  days = (date2 - dateTest).Days;
}