Find number of years, months and days between two dates using C#
Recently I ran into a situation where I had the start date and the end date and had to store the start date and the difference between the end and the start date (in terms of years, months, days) as string.
Here is a C# code to do that:
public static string DateDiff(DateTime startDate, DateTime endDate) { string timeStr = string.Empty; int yr = 0; int mth = 0; int days = 0; TimeSpan ts = new TimeSpan(); ts = endDate.Subtract(startDate); yr = (ts.Days/365); do { for(int i=0; i <= 12; i++) { if(endDate.Subtract(startDate.AddYears(yr).AddMonths(i)).Days > 0) { mth = i; } else { break; } } if(mth > 12) yr = yr + 1; }while(mth > 12); days = endDate.Subtract(startDate.AddYears(yr).AddMonths(mth)).Days; if(yr > 0) timeStr += yr.ToString() + "y"; if(mth > 0) timeStr += mth.ToString() + "m"; if(days > 0) timeStr += days.ToString() + "d";
return(timeStr);
}
How would you have done this?
Popularity: 5% [?]

Comments(3)


























Wouldn’t it be nice if IE7 provided more control over how you want to use your tabs, had an ad filter like 




