Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find year and month difference between two dates?

Tags:

c#

asp.net

DateTime dayStart;
DateTime dateEnd;

TimeSpan ts = dateEnt - dateStart;

Print : ... Year(s) and ... Month(s)

how can I calculate it?

.net framework 2.0
c#

asp.net project.

like image 678
Bilgin Kılıç Avatar asked Jan 20 '11 14:01

Bilgin Kılıç


2 Answers

You should first read this article from Jon Skeet, specially from the text "Introducing periods and period arithmetic" it gets interesting for you.

So, you have to define when a certain period is a change in month, in year etc.

Noda-time already contains a lot of functions for this. But I don't think it is released yet.

like image 181
GvS Avatar answered Sep 27 '22 19:09

GvS


Following will calculate the age in years, months, days

        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);
like image 28
user2481162 Avatar answered Sep 27 '22 19:09

user2481162