How to Add Hours to Date Object in JavaScript
Surprisingly, the JavaScript Date API does not provide a way to add hours to a Date object.
But we can create our own function to do this.
We don’t want to mutate the original Date object, so we can first create a new Date object and then manually set the hours.
function addHours(date, hours) {
const newDate = new Date(date);
newDate.setHours(newDate.getHours() + hours);
return newDate;
}
We can use this utility function like so:
const date = new Date(); // Fri Feb 26 2021 20:08:30
const newDate = addHours(date, 1); // Fri Feb 26 2021 21:08:30