Get different from dates - Node.js Date

Node.js examples for Date:Date Calculation

Description

Get different from dates

Demo Code



// from http://trentrichardson.com/2011/09/29/looping-through-dates-with-javascript/
Date.prototype.diff = function (date2, parts) {
    var d1 = new Date(this.getTime()),
        d2 = new Date(date2.getTime()),
        pm = d1 <= d2 ? 1 : -1,/* ww w .j  av  a2 s.c  o m*/
        result = { },
        factors = { weeks:(1000 * 60 * 60 * 24 * 7), days:(1000 * 60 * 60 * 24), hours:(1000 * 60 * 60), minutes:(1000 * 60), seconds:1000, milliseconds:1 };

    if (parts === undefined)
        parts = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds'];
    else if (typeof(parts) == "string")
        parts = [parts];

    for (var i = 0, l = parts.length; i < l; i++) {
        var k = parts[i];
        result[k] = 0;

        if (factors[k] === undefined) {
            inaWhile: while (true) {
                d2.adjust(k, -1 * pm);
                if ((pm === 1 && d1 > d2) || (pm === -1 && d1 < d2)) {
                    d2.adjust(k, 1 * pm);
                    break inaWhile;
                }
                result[k]++;
            }
        }
        else {
            var tmpDiff = Math.abs(d2.getTime() - d1.getTime());
            result[k] = Math.floor(tmpDiff / factors[k]);
            d2.adjust(k, result[k] * -1 * pm);
        }
        result[k] *= pm;
    }

    if (parts.length == 1)
        return result[parts[0]];
    return result;
};


function addZero(val) {
    return (parseInt(val) < 10) ? "0" + val : val;
}


function isCurrentHour(chosenHour) {
    var cmpdate = new Date(chosenHour.getTime());
    return (new Date().setMinutes(0, 0, 0) === cmpdate.setMinutes(0, 0, 0));
}

function isCurrentDay(chosenDay) {
    var cmpdate = new Date(chosenDay.getTime());
    return (new Date().setHours(0, 0, 0, 0) === cmpdate.setHours(0, 0, 0, 0));
}

Related Tutorials