-
Notifications
You must be signed in to change notification settings - Fork 7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
duration can be in inconsistent state after subtraction #2166
Comments
The problem seems to be more extensive than shown in that first fiddle. http://jsfiddle.net/9cs8o1v1/4/ http://jsfiddle.net/9cs8o1v1/5/ |
Now I think this issue runs deeper than
The final assert fails, as |
I meet the same problem. It seems that moment only bubble up values (e.g.: var d = moment.duration('P1D').subtract(1, 'hour');
d.toString(); // P1DT1H
d.days(); // 1
d.hours(); // -1
d.asHours(); // 23 As you can see, the var d = moment.duration(moment.duration('P1D').subtract(1, 'hour').asMilliseconds());
d.toString();// PT23H
d.hours(); // 23 |
I think this is the same issue (version : 2.9.0): var a = moment('2015/01/01'),
b = moment('2015/01/31');
console.log(b.diff(a, 'days')); // 30 - correct
console.log(moment.duration({from: a, to: b}).as('days')); // 30 - correct
b = moment('2015/02/01');
console.log(b.diff(a, 'days')); // 31 - correct
console.log(moment.duration({from: a, to: b}).as('days')); // 30 - incorrect |
I've run across this, too. Not much to add, but this can be demonstrated with both .add() (using a negative value) and .subtract():
You can coax the desired value by constructing a new duration from the result of asMilliseconds():
|
I agree we have a problem here. The main issue is that
One way to fix this is to add code to bubble so it works well with a mix of positive/negative values. If it detects positive/negative, it will just convert everything to ms, and then bubble that. |
Improved duration bubbling, fixes #2166
I haven't explored to see all the circumstances that can cause it, but I notice that a duration's fields do not necessarily get normalized after subtraction. Depending on how you do the same subtraction (conceptually), you get different results.
Here's a fiddle to see the issue in action:
http://jsfiddle.net/9cs8o1v1/3/
A test that would break due to this bug is:
As you can see in the fiddle,
subtract1.months()
yields-5
, whilesubtract2.months()
yields7
.The text was updated successfully, but these errors were encountered: