Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 2 days in years, months and days [duplicate]

Tags:

c#

.net

datetime

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();
    }
}
like image 439
Kris Avatar asked Dec 15 '14 09:12

Kris


2 Answers

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.

like image 183
Jon Skeet Avatar answered Nov 15 '22 03:11

Jon Skeet


To get the delta, just subtract directly:

var delta = p1 - p2;

This gives you a TimeSpan. From there, you have access to .Days. Months and years, however, are much more complicated. If you want the difference in those terms, you'll have to compare the properties of p1 and p2 directly (or: as Jon says: use Noda Time)

like image 23
Marc Gravell Avatar answered Nov 15 '22 04:11

Marc Gravell