Getting date difference in Years,Month and Days.

Vishalneeraj-24503
Posted by Vishalneeraj-24503 under Visual Studio category on | Points: 40 | Views : 1502
Write below code:-
public string DateDiff(DateTime Dt1, DateTime Dt2)
{
TimeSpan ltsT1 = Dt2 - Dt1;
Decimal D1 = Convert.ToDecimal(ltsT1.TotalDays) / 365.25M;
Decimal D2 = Decimal.Floor(D1);
Decimal M1 = (D1 - D2) * 12;
Decimal M2 = Decimal.Floor(M1);
Decimal Day1 = (M1 - M2) * 24;
Decimal Day2 = Decimal.Floor(Day1);
return D2 + " Years " + M2 + " Months " + Day2 + " Days ";
}

To use it,i have added 5 months in current date.
string dt = DateDiff(DateTime.Now, DateTime.Now.AddMonths(5));

Output:-
0 Years 5 Months 0 Days

Comments or Responses

Login to post response