How to Add Hours to JavaScript Date Object

JavaScript setHours() method sets the hour of a date object. JavaScript getHours() method returns the hour (from 0 to 23) of the specified date and time. Using JavaScript setHours() and getHours() method you can easily add hours to Date object. Here we’ll provide a short and simple code to add hours to JavaScript Date object.

Use the following JavaScript code to add hours to current date.

Date.prototype.addHours = function(h){
    return this;

Provide the hours as a parameter in addHours() function which you want to add to the Date object.

new Date().addHours(5);

If you display the above code in the alert box, you’ll see 5 hours are added to the current date.

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

Leave a reply

Connect With CodexWorld