Format A TimeSpan With Years

A TimeSpan doesn’t have a sensible concept of “years” because it depends on the start and end point. (Months is similar – how many months are there in 29 days? Well, it depends…)

To give a shameless plug, my Noda Time project makes this really simple though:

using System;
using NodaTime;

public class Test
{
    static void Main(string[] args)
    {
        LocalDate start = new LocalDate(2010, 6, 19);
        LocalDate end = new LocalDate(2013, 4, 11);
        Period period = Period.Between(start, end,
                                       PeriodUnits.Years | PeriodUnits.Days);

        Console.WriteLine("Between {0} and {1} are {2} years and {3} days",
                          start, end, period.Years, period.Days);
    }
}

Output:

Between 19 June 2010 and 11 April 2013 are 2 years and 296 days

Leave a Comment