Difference between 2 days in years, months and days

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

With time and subtraction, I only get days, but you can output them through 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();
    }
}

      

+3


source to share


2 answers


.NET types don't give you a decent answer to this question without having to write code to try one answer and tweak it accordingly, but Noda Time 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 choose to use Noda Time for this, you can simply do it in your method, using DateTime

elsewhere and converting between types ... but usually it would be better to use Noda Time more widely. The goal is to allow your code to be clearer than simple to use DateTime

.

+12


source


To get the delta, just subtract directly:

var delta = p1 - p2;

      



It gives you TimeSpan

. From there, you have access to .Days

. However, months and years are much more complicated. If you want a difference in these terms, you have to directly compare properties p1

and p2

(or: as John says: use Noda Time)

+2


source







All Articles