計算倆個時間之間隔多少月(C#)

2010-08-28 10:50:18來源:西部e網(wǎng)作者:

using System;

class Test
{
  static int MonthsDiff(DateTime dt1, DateTime dt2)
  {
    int m = (dt2 - dt1).Days / 31;
    while (dt1.AddMonths(m) < dt2)
      m++;
    return m;
  }

  static void Main()
  {
    DateTime dt1 = new DateTime(2005, 1, 1);
    DateTime dt2 = new DateTime(2008, 4, 1);
    int n = MonthsDiff(dt1, dt2);
    Console.WriteLine(n);
  }
}

關鍵詞:C#