Search code examples
c#asp.netvb.netdatediffdays

convert number of days into years,months,days


I need to convert the number of days into years, months, days.

Example: A Employee Experience to be calculated as per his Date of join(DOJ) and date of Relieve(DOR). We have a DOJ, DOR and Number of Days he is worked as a employee.

Have to Calculate the How many Years and Months and Days.

Example       : DOJ = 14 Feb 2000
                DOR = 08 aug 2013
Output        : 13 Years - 5 Months - 25 Days

Thanks in Advance....


Solution

  • This works for me:

    var dor = new DateTime(2013, 08, 08);
    var doj = new DateTime(2000, 02, 14);
    
    var totalmonths = (dor.Year - doj.Year) * 12 + dor.Month - doj.Month;
    totalmonths += dor.Day < doj.Day ? -1 : 0;
    
    var years = totalmonths / 12;
    var months = totalmonths % 12;
    var days = dor.Subtract(doj.AddMonths(totalmonths)).Days;