Calculate years, months, days between two dates

I am trying to display the years, months and days between two dates in a C# application that I am creating. (Using console for testing purposes)

I'm using NodaTime to achieve this but I am having issues rounding months up.

I have read most of the questions and answers here but didn't find anything that I could benefit from.

Most of the time the function works but sometimes it doesn't add the months if days > 30 (which would add a month)

I am using this code for testing

LocalDate start = new LocalDate(2017, 10, 16);
LocalDate end = new LocalDate(2018, 1, 15);
Period period = Period.Between(start, end);

Console.WriteLine("{0} years, {1} months, {2} days",
                              period.Years, period.Months, period.Days);
Console.ReadLine();

(2017, 10, 16) and (2018, 1, 15) should display as 3 months but they show as 2 months and 30 days ( I've tried to add +1 to period.Days but it's showing as 31 days after I do that). I need the end date included when I display the format.

Is there anything I can use to achieve what I need ? I need to show the correct format: 2 years, 11 months, 3 days

Jon Skeet
people
quotationmark

The issue is indeed that you're using the "include end date in calculation" in timeanddate.com. The solution isn't to add a day to the period in Noda Time - it's to add a day to the end date before you perform the calculation:

Period period = Period.Between(start, end.PlusDays(1));

That will then give you your expected output:

using System;
using NodaTime;

class Test
{
    static void Main()
    {
        LocalDate start = new LocalDate(2017, 10, 16);
        LocalDate end = new LocalDate(2018, 1, 15);
        Period period = Period.Between(start, end.PlusDays(1));

        Console.WriteLine(
            $"{period.Years} years, {period.Months} months, {period.Days} days");
    }
}

Output:

0 years, 3 months, 0 days

When thinking about "between" questions like this, I like to try to think of really simple examples.

What's the period between January 23rd 2018 and January 24th 2018? Noda Time and I both say "1 day". (Add 1 day to January 23rd and you get January 24th.) If you're talking about the period of time covered by the date interval of January 23rd 2018 to January 24th 2018, then that's two days.

people

See more on this question at Stackoverflow