public static void DateTimeDiff(DateTime begin, DateTime end, out int months, out int days, out int senconds)
{
days = 0;
int totalSeconds = (int)end.Subtract(begin).TotalSeconds;
int totalDays = (int)end.Subtract(begin).TotalDays;
int restSenconds = totalSeconds % (24 * 3600);
int approximateMonths;
if (end.Day > begin.Day || (end.Day == begin.Day && end.Hour >= begin.Hour))
{
approximateMonths = (end.Year - begin.Year) * 12 + (end.Month - begin.Month);
}
else
{
approximateMonths = totalDays / 30;
}
DateTime tempDate = begin.AddMonths(approximateMonths);
if (tempDate > end)
{
while (tempDate > end)
{
approximateMonths--;
tempDate = tempDate.AddMonths(-1);
}
}
else
{
while (tempDate < end)
{
tempDate = tempDate.AddMonths(1);
if (tempDate < end)
approximateMonths++;
}
}
tempDate = begin.AddMonths(approximateMonths);
while (tempDate < end)
{
tempDate = tempDate.AddDays(1);
if (tempDate <= end)
days++;
}
senconds = restSenconds;
months = approximateMonths;
if (months > 0)
{
int beginDaysInMonth = DateTime.DaysInMonth(begin.Year, begin.Month);
int endDaysInMonth = DateTime.DaysInMonth(end.Year, end.Month);
if (beginDaysInMonth > endDaysInMonth && end.Day == endDaysInMonth && begin.Day > endDaysInMonth && days < endDaysInMonth)
{
months--;
days = 0;
tempDate = begin.AddMonths(months).AddDays(days).AddSeconds(senconds);
while (tempDate < end)
{
tempDate = tempDate.AddDays(1);
if (tempDate <= end)
days++;
}
}
if (begin.Day > end.Day && begin.AddMonths(months).AddDays(days).AddSeconds(senconds) > end)
{
months--;
days = 0;
tempDate = begin.AddMonths(months).AddDays(days).AddSeconds(senconds);
while (tempDate < end)
{
tempDate = tempDate.AddDays(1);
if (tempDate <= end)
days++;
}
}
}
}
计算两个日期之间间隔的月份与除去月份后余下的天数。