Date.diff not working correctly #1072

Open
overheadhunter opened this Issue Nov 18, 2011 · 1 comment

Projects

None yet

1 participant

@overheadhunter
overheadhunter commented Nov 18, 2011 edited by arian

There seems to be a rounding issue with Date.diff in Mootools More, which can be reproduced easily like this:

var a = new Date(2010, 05, 01);
var b = new Date(2010, 04, 01);
var x = new Date(2012, 11, 01);

alert(a.diff(x, 'month')); //30
alert(b.diff(x, 'month')); //32 (should be 31)

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/359889-date-diff-not-working-correctly?utm_campaign=plugin&utm_content=tracker%2F22069&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F22069&utm_medium=issues&utm_source=github).
@overheadhunter

Found an old implementation (moo 1.2), that works with my example given on 2011-11-18:

    diff: function(d, resolution){
        resolution = resolution || 'day';
        if ($type(d) == 'string') d = Date.parse(d);

        switch (resolution){
            case 'year':
                return d.get('year') - this.get('year');
            case 'month':
                var months = (d.get('year') - this.get('year')) * 12;
                return months + d.get('mo') - this.get('mo');
            default:
                var diff = d.get('time') - this.get('time');
                if (Date.units[resolution]() > diff.abs()) return 0;
                return ((d.get('time') - this.get('time')) / Date.units[resolution]()).round();
        }

        return null;
    }

current (1.4.0.1):

    diff: function(date, resolution){
        if (typeOf(date) == 'string') date = Date.parse(date);

        return ((date - this) / Date.units[resolution || 'day'](3, 3)).round(); // non-leap year, 30-day month
    },
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment