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.

Example:
Calculate Age in Years, Months and Days.

Solution:
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)
    {
        Years++;
        newDate = newDate.AddYears(1);
    }
    Years--;
    fromDate = fromDate.AddYears(Years);
    newDate = fromDate;
    while (newDate <= toDate)
    {
        Months++;
        newDate = newDate.AddMonths(1);
    }
    Months--;
    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