date js add hours code example

Example 1: date add 1 hour javascript

//JS
function addHoursToDate(date, hours) {
  return new Date(new Date(date).setHours(date.getHours() + hours));
}

//TS
function addHoursToDate(date: Date, hours: number): Date {
  return new Date(new Date(date).setHours(date.getHours() + hours));
}

let myDate = new Date();

console.log(myDate)
console.log(addHoursToDate(myDate,2))

Example 2: date add hours javascript

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

Example 3: add 2 for hours in date timestamp js

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

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