I use NodaTime library to get period between two days, but sometimes I get partly negative period between two dates:
var start = DateTime.Now;
var end = start.AddDays(7).AddMinutes(-1);
//6 days, 24 hours and -1 minutes
var period = Period.Between(LocalDateTime.FromDateTime(start), LocalDateTime.FromDateTime(end));
How can I prevent such behavior? At this moment I already have found one solution:
//6 days, 23 hours and 59 minutes, but no weeks, months, years
var duration = period.ToDuration();
But duration object is not contrain weeks, months, years and so on.
TL;DR: Update to Noda Time 2.0.2.
This was a bug in 2.0.0 and 2.0.1 of Noda Time. Brief testing suggests it wasn't an issue in earlier versions.
The problem was due to an optimization when trying to obtain the time parts of a period between two LocalDateTime
values. Consider finding the difference between these values using all units:
start: 2017-05-22T12:00:00
end: 2017-05-25T11:30:00
We'd start by finding the days portion: 2 days (not 3, because that would overshoot). That would leave us finding the time units between:
updated-start: 2017-05-24T12:00:00
end: 2017-05-25T11:30:00
When trying to find the number of hours, it would first find the number of days between the two dates, then multiply by 24, and then the number of hours between the results - so we'd end up with 24 hours, which then overshot by 30 minutes.
The fix for this was basically an overhaul of Period
- see PR 825 and PR 826. PR 825 was then cherry-picked into the 2.0.x branch, and 2.0.2 was released on May 22nd 2017.
See more on this question at Stackoverflow