Difference between two dates in C#

In a senario I need to find out the difference between two dates.For example Start date is 01/01/2012 and To Date is 01/10/2013 .I need to get the output as 1.9 years.

int tDays=(ToDate.Subtract(FromDAte).Days+1);
int years = tDays / 365;
int months = (tDays % 365) / 31;

But this calculation is wrong in case of Leap years.

Jon Skeet
people
quotationmark

My Noda Time library is built for exactly this sort of thing:

LocalDate start = new LocalDate(...);
LocalDate end = new LocalDate(...);
Period period = Period.Between(start, end);
Console.WriteLine("{0} years, {1} months, {2} days",
                  period.Years, period.Months, period.Days);

Note that this will also deal with the fact that months aren't always the same length - so for example, February 1st to March 1st 2013 (28 days) == 1 month, whereas March 1st to March 29th (also 28 days) == 0 months, 28 days.

That will get you months, years and days - I'm not sure where you get "1.9" from based on your example, unless you're using "years.months", which I'd strongly recommend against as it looks like you mean "very nearly 2 years".

people

See more on this question at Stackoverflow