Adding hours to JavaScript Date object? Adding hours to JavaScript Date object? javascript javascript

Adding hours to JavaScript Date object?


JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:

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


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

Test:

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


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