Add Hours to a Date in JavaScript

avatar

Borislav Hadzhiev

Fri Jan 21 20222 min read

Add Hours to a Date in JavaScript #

To add hours to a Date in JavaScript:

  1. Use the getTime() method to get the number of milliseconds since the Unix Epoch.
  2. Use the setTime() method, passing it the result of calling getTime plus the hours converted to milliseconds.
index.js
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.

If no 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.

index.js
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.

Note that the 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.
index.js
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.

We passed the timestamp to the 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.

In general, mutating function arguments is a bad practice, as passing the same parameter to the same function multiple times returns different results.
Use the search field on my Home Page to filter through my more than 1,000 articles.