✒️
Here are my favorite tips to land the software engineer interview.
Here are my favorite tips to land the software engineer interview.
How to Add Hours to Date Object in JavaScript
Published Mar 5, 2021
∙ Updated May 2, 2022
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