class Program
{
static void Main(string[] args)
{
DateTime date1 = new DateTime(2020,7,9);
DateTime date2 = new DateTime(2022,7,2);
TimeInterval(date1,date2);
}
private static void TimeInterval(DateTime date1, DateTime date2)
{
int year=0, month=0, day=0, week=0;
//首先计算年
year = date2.Year - date1.Year;
/**
* 1.如果date2的月份大于date1的月份
* ***/
if (date2.Month > date1.Month)
{
month = date2.Month - date1.Month;
}
/*2.若date2的月份小于date1的月份
*/
else if (date2.Month < date1.Month)
{
month = date2.Month + 12 - date1.Month;
year--;
}
/*
* 3.若date2的月份和date1的月份相等,并且date2的号数小于date1的号数
*/
else if (date2.Month == date1.Month && date2.Day<date1.Day)
{
month = date2.Month + 12 - date1.Month;
year--;
}
if (date2.Day > date1.Day)
{
day = date2.Day - date1.Day;
}
else if (date2.Day<date1.Day)
{
day = DateTime.DaysInMonth(date2.Year, date2.Month - 1) + date2.Day - date1.Day;
month--;
}
week = day / 7;
day = day % 7;
Console.WriteLine(date1.ToString() +" 和 "+date2.ToString()+" 间隔\n "+year+"年"+month+"月"+week+"周"+day+"天");
}
}
C#计算两个时间差(精确到年月周日)
最新推荐文章于 2022-09-23 16:52:28 发布