Feb 5, 2012

Difference in Years, Months and Days in C#

In an earlier post, I have shared the function of calculating Date difference in Year(s), Month(s) and Day(s) in SQL Server.

Recently one of my friend had a requirement to calculate the same in ASP.Net, so I created a function to achieve the same in ASP.Net / C# and thought of posting the same on my blog.

Calculate Age in Years, Months and Days.

Function DateDiffInYearMonthDay take two arguments of date datatype and returns the result in text format
Ex - 18 years, 2 months, 3 days

private string DateDiffInYearMonthDay(DateTime fromDate, DateTime toDate)
    int Years=0, Months=0, Days=0;
    DateTime newDate;
    newDate = fromDate;
    while (newDate <= toDate)
        newDate = newDate.AddYears(1);
    fromDate = fromDate.AddYears(Years);
    newDate = fromDate;
    while (newDate <= toDate)
        newDate = newDate.AddMonths(1);
    fromDate = fromDate.AddMonths(Months);
    Days = toDate.Subtract(fromDate).Days;
    return Years.ToString() + "years," + Months.ToString() + " months," + Days.ToString() + " days";      

    Choose :
  • OR
  • To comment
No comments:
Write Comments