Skip to content
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

Date diff in months returning possible incorrect value - less for later date #2109

Closed
awbacker opened this issue Dec 18, 2014 · 4 comments
Closed

Comments

@awbacker
Copy link

I am using moment for some date duration validation, and got a failing test around a month border. We are trying to get the months difference, and a later date is showing a smaller difference. Is the months difference something we shouldn't rely on, or is this a bug, or expected behavior due to the annoying month of February?

// notice how the diff for 01-Feb to 01-May goes DOWN from 30-Apr.  It goes back up 
moment('2014-02-01').diff(moment('2014-04-30 23:59:59'), 'months', true);  // -3.034482359514687
moment('2014-02-01').diff(moment('2014-05-01 23:59:59'), 'months', true);  // -3.0338979127432517
moment('2014-02-01').diff(moment('2014-05-02 23:59:59'), 'months', true);  // -3.0677962178279974

Doing the same without times results in -3 for two different dates:

moment('2014-02-01').diff(moment('2014-04-30'), 'months', true);  // -3
moment('2014-02-01').diff(moment('2014-05-01'), 'months', true);  // -3

Edit: Downloaded moment.min.js yesterday, v2.8.4

@webglider
Copy link

This is happening because while adjusting days, to convert the days difference into months it takes the average of number of days in both the months involved (i.e Feb and April in first case , Feb and May in second case). Since may has more days than April, one day in the second case weighs less than one day in the first case and that is why it decreases.

I guess the decision to use this implementation was taken after a lot of discussion:
#571

@awbacker
Copy link
Author

Yeah, I went reading the code to see if I could figure it out. I saw the thing about average days too, and figured that might be what was causing this. After some quiet reflection, I don't see how a unit called "months" can ever be accurate, or even what accurate means in this case. The best you can do is have defined behavior. What moment.js has now is about as good as it can get, I think.

I think the only alternative is for me to define "1 month" as being from DD/MM to DD/(MM+1) and see if that satisfies 'em.

@Chipintoza
Copy link

here is bag!
just try

var a = moment([2019, 10, 1]);
var b = moment([2019, 10, 11]);
console.log(a.diff(b, 'months', true))
console.log(b.diff(a, 'months', true))

its log difference values

@Chipintoza
Copy link

Sorry. i understand how you calculate diff

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants