Proper date manipulation in JavaScript

Date manipulation in JavaScript is rather primitive and the "standard" way of adding/subtracting time is error prone. The standard way is doing following:
var four_hours_ago = new Date();
four_hours_ago.setUTCHours( four_hours_ago.getUTCHours() - 4);

The problem is if four_hours_ago.getUTCHours() is 2, then you'll set hours to -2 - which will be incorrect.

The proper way to do this is following:

function addToDate(date, hours, minutes) {
    var m_secs = date.getTime();
    var local_offset = date.getTimezoneOffset() * 60 * 1000;
    var utc_m_secs = m_secs + local_offset;

    if(hours)
        utc_m_secs += hours * 60 * 60 * 1000;
    if(minutes)
        utc_m_secs += minutes * 60 * 1000;

    return new Date(utc_m_secs);
}

var four_hours_ago = addToDate(new Date(), -4);

Ok, hope somebody can find this useful as I have spent a hour or two fixing this bug :-)

Code · Code rewrite · JavaScript · Tips 3. Nov 2008
© Amir Salihefendic. Powered by Skeletonz.