Difference between 2 days in years, months and days

I need to output the difference between 2 days in years, months and days.

With timespan and subtract i only get the days but is it possible to output in years, months and days.

This is what i have so far:

public string Leeftijdsverschil(DateTime p1, DateTime p2)
{
    if (p1 > p2)
    {
        DateTime verschil = p1.Subtract(TimeSpan.FromTicks(p2.Ticks));
        return verschil.ToString();
    }
    else
    {
        DateTime verschil = p2.Subtract(TimeSpan.FromTicks(p1.Ticks));
        return verschil.ToString();
    }
}
Jon Skeet
people
quotationmark

The .NET types don't give you a decent answer to this without having to write code to try one answer and adjust appropriately, but my Noda Time project is designed to handle this sort of thing. For example:

LocalDate x = new LocalDate(2013, 5, 21);
LocalDate y = new LocalDate(2014, 12, 15);
Period p = Period.Between(x, y);
Console.WriteLine("{0} {1} {2}", p.Years, p.Months, p.Days);

Result:

1 6 24

(i.e. 1 year, 6 months and 24 days)

If you decide to use Noda Time for this, you could just do it within your method, using DateTime elsewhere and converting between the types... but it would generally be better to embrace Noda Time more widely. The aim is for it to allow your code to be clearer than just using DateTime.

people

See more on this question at Stackoverflow