views:

2784

answers:

4

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?

+3  A: 

There is an add in the Datejs library.

And here are the JavaScript date methods. kennebec wisely mentioned getHours() and setHours();

Nosredna
+4  A: 

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;   
}
Jason Harwig
+11  A: 
Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

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

kennebec
Wow - easier than I thought.
Jeff Meatball Yang
I don't think this works---test it on something with hour 23, for example? Jason Harwig's answer is what came to mind for me.
Domenic
A: 

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.

Tahir Hassan