/*********************************************************
*作者:flashicp
***************************************************************/
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#实现计算两个日期月数差
博客展示了一段C#代码,定义了一个Test类,其中包含MonthsDiff方法用于计算两个DateTime对象之间相差的月数,并在Main方法中进行测试。最后还引导读者思考计算天数、星期数差,以及编写判断两个时间相隔的类。
1376

被折叠的 条评论
为什么被折叠?



