Adding hours to Javascript Date object?

Adding hours to Javascript Date object?

It amazes me that Javascript’s Date object does not implement an add function of any kind.
I simply want a function that can do this:
var now = Date.now();
var fourHoursLater = now.addHours(4);

function Date.prototype.addHours(h) {

// how do I implement this?

}

I would simply like some pointers in a direction.

Do I need to do string parsing?
Can I use setTime?
How about milliseconds?

Like this:
new Date(milliseconds + 4*3600*1000 /*4 hrs in ms*/)?

This seems really hackish though – and does it even work?

Solutions/Answers:

Solution 1:

JavaScript itself has terrible Date/Time API’s. This is the only way to do it in pure JavaScript. I’d recommend using Datejs – as suggested by Nosredna – if you’re doing a lot of date manipulation, though.

Date.prototype.addHours = function(h) {
  this.setTime(this.getTime() + (h*60*60*1000));
  return this;
}

Solution 2:

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

Test:

alert(new Date().addHours(4));

Solution 3:

The below code is to add 4 hours to date(example today’s date)

var today = new Date();
today.setHours(today.getHours() + 4);

It will not cause error if you try to add 4 to 23 (see the docs):

If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly

Solution 4:

It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.

Date.prototype.addHours= function(h){
    var copiedDate = new Date(this.getTime());
    copiedDate.setHours(copiedDate.getHours()+h);
    return copiedDate;
}

This way you can chain a bunch of method calls without worrying about state.

Solution 5:

The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.

this.setUTCHours(this.getUTCHours()+h);

will add h hours to this independent of time system peculiarities.
Jason Harwig’s method works as well.

Solution 6:

You can use the momentjs http://momentjs.com/ Library.

var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();