Borislav Hadzhiev
Fri Jan 21 2022·2 min read
Photo by Levon Vardanyan
To add hours to a Date in JavaScript:
getTime()
method to get the number of milliseconds since the Unix
Epoch.setTime()
method, passing it the result of calling getTime
plus
the hours converted to milliseconds.function addHours(numOfHours, date = new Date()) { date.setTime(date.getTime() + numOfHours * 60 * 60 * 1000); return date; } // 👇️ Add 1 hour to current date const result = addHours(1); // 👇️ Add 2 hours to another date const date = new Date('2022-03-14T09:25:30.820'); // 👇️ Mon Mar 14 2022 11:25:30 console.log(addHours(2, date));
We created a reusable function that takes the number of hours and a Date
object and ads the hours to the date.
Date
object is provided to the function, it uses the current date.The getTime method returns the number of milliseconds elapsed between 1st of January, 1970 00:00:00 and the given date.
We multiplied the number of hours by 60 * 60 * 1000
because we need to convert
the value to milliseconds, when passing it to the
setTime
method.
The setTime()
method takes a number that represents the milliseconds since the
1st of January, 1970 and sets the value on the date.
This approach automatically takes care of the scenario where adding X hours pushes us into the next day, month or year.
const date = new Date('2022-03-14T23:25:30.820'); const numOfHours = 10; date.setTime(date.getTime() + numOfHours * 60 * 60 * 1000); // 👇️ Tue Mar 15 2022 09:25:30 console.log(date);
Adding 10
hours to the date successfully changed the day of the month to the
15th
.
setTime
method mutates the Date
object it was called on. If you don't want to change the Date
in place, you can create a copy of it before calling the method.function addHours(numOfHours, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setTime(dateCopy.getTime() + numOfHours * 60 * 60 * 1000); return dateCopy; } // 👇️ Add 2 hours to another date const date = new Date('2022-03-14T09:25:30.820'); const result = addHours(2, date); console.log(result); // 👉️ Mon Mar 14 2022 11:25:30 console.log(date); // 👉️ Mon Mar 14 2022 09:25:30 (didn't change original)
We used the getTime
method to get the number of milliseconds elapsed between
1st of January, 1970 00:00:00 and the given date.
Date()
constructor to create a copy of the Date
object, so we don't mutate it in place when calling the setTime
method.Copying the date is quite useful when you have to use the original Date
object
in other places in your code.