如何找到两个日期之间的年和月差异?

Bil*_*lıç 7 c# asp.net

DateTime dayStart;
DateTime dateEnd;

TimeSpan ts = dateEnt - dateStart;
Run Code Online (Sandbox Code Playgroud)

打印:...年份和...月份

我怎么计算呢?

.net framework 2.0
c#

asp.net项目.

GvS*_*GvS 7

你应该先阅读这篇文章乔恩斯基特,特意从文"介绍周期和周期算术"它有趣的为您服务.

因此,您必须定义某个时段是月份,年份等的变化.

Noda-time已经包含了很多功能.但我认为它尚未发布.


小智 5

以下将计算年,月,日的年龄

        DateTime dob = "10/18/1981";  // date of birth
        DateTime now = DateTime.Now;

        // Swap them if one is bigger than the other
        if (now < dob)
        {
            DateTime date3 = now;
            now = dob;
            dob = date3;
        }
        TimeSpan ts = now - dob;
        //Debug.WriteLine(ts.TotalDays);

        int years = 0;
        int months = 0, days=0;
        if ((now.Month <= dob.Month) && (now.Day < dob.Day))  // i.e.  now = 03Jan15,  dob = 23dec14  
        {
            // example: March 2010 (3) and January 2011 (1); this should be 10 months.  // 12 - 3 + 1 = 10
            years = now.Year - dob.Year-1;
            months = 12 - dob.Month + now.Month-1;
            days = DateTime.DaysInMonth(dob.Year, dob.Month) - dob.Day + now.Day;

            if(months==12)
            {
                months=0;
                years +=1;
            }
        }
        else if ((now.Month <= dob.Month) && (now.Day >= dob.Day)) // i.e.  now = 23Jan15,  dob = 20dec14  
        {
            // example: March 2010 (3) and January 2011 (1); this should be 10 months.  // 12 - 3 + 1 = 10
            years = now.Year - dob.Year - 1;
            months = 12 - dob.Month + now.Month;
            days = now.Day - dob.Day;
            if (months == 12)
            {
                months = 0;
                years += 1;
            }
        }
        else if ((now.Month > dob.Month) && (now.Day < dob.Day))  // i.e.  now = 18oct15,  dob = 22feb14  
        {
            years = now.Year - dob.Year;
            months = now.Month - dob.Month-1;
            days = DateTime.DaysInMonth(dob.Year, dob.Month) - dob.Day + now.Day;
        }
        else if ((now.Month > dob.Month) && (now.Day >= dob.Day))  // i.e.  now = 22oct15,  dob = 18feb14  
        {
            years = now.Year - dob.Year;
            months = now.Month - dob.Month;
            days = now.Day - dob.Day;
        }
        Debug.WriteLine("Years: {0}, Months: {1}, Days: {2}", years, months, days);
Run Code Online (Sandbox Code Playgroud)


Guf*_*ffa 3

这取决于您想要准确计算什么。

您无法将 a 中的值转换TimeSpan为精确的年份和月份,因为年份和月份的长度各不相同。您可以像这样计算大约的年份和月份:

int years = ts.Days / 365;
int months = (ts.Days % 365) / 31;
Run Code Online (Sandbox Code Playgroud)

如果您想要确切的差异,则必须比较这些DateTime值。