Date difference from Noda Time is correct?

2019-07-18 21:10发布

问题:

DateTime dtStart = new DateTime(2015,7,28);
LocalDate ldtStart = LocalDate.FromDateTime(dtStart);

DateTime dtEnd = new DateTime(2017, 2, 1);
LocalDate ldtEnd = LocalDate.FromDateTime(dtEnd);

Period period = Period.Between(ldtStart, ldtEnd, PeriodUnits.YearMonthDay);

Result for above:
period.Years -> 1
period.Months -> 6
period.Days -> 4

As you can see the difference i got from Noda Time library.
But i get different result for https://www.easycalculation.com/date-day/age-calculator.php
Result for above link:
1 years, 6 months, and 1 days

Start Date: 28th July 2015
End Date: 1st Feb 2017

Can someone please tell me that the result i got from noda time plugin is more accurate then the link I provided?

回答1:

"More accurate" requires a specification of how you want to compute the difference. There's no single right answer here. As documented, Noda Time works element-wise. So if you add 1 year, 6 months and 4 days to 28th July 2015 you get:

  • Adding 1 year: 28th July 2016
  • Adding 6 months: 28th January 2017
  • Adding 4 days: 1st February 2017

The code used for the site is available on the site itself. It looks like that's taking a rather more naïve approach.

In particular, if you ask it how old someone born on January 31st 2017 is on February 1st 2017, they'll say they're -2 days old. I don't think that's right...



回答2:

From 28th July 2015 to 1st August 2015 is 4 days and from 1st August 2015 to 1st Feb 2017 is exactly one and a half year.

NodaTime shows you correct information. You also could check with this link.

You could try to change in your link date from 28th July 2015 to 29th July 2015 or 30th July 2015 and you will see invalid input.