Subtract Hours from a Date in JavaScript


Borislav Hadzhiev

Last updated: Jul 25, 2022


Photo from Unsplash

Subtract Hours from a Date in JavaScript #

To subtract hours from a date:

  1. Use the getHours() method to get the hours of the specific date.
  2. Use the setHours() method to set the hours for the date.
  3. The setHours method takes the hours as a parameter and sets the value for the date.
function subtractHours(numOfHours, date = new Date()) { date.setHours(date.getHours() - numOfHours); return date; } // 👇️ Subtract 1 hour from the current date const result = subtractHours(1); // 👇️ Subtract 2 hours from another date const date = new Date('2022-04-27T08:30:10.820'); // 👇️ Wed Apr 27 2022 06:30:10 console.log(subtractHours(2, date));

We created a reusable function that takes the number of hours and a Date object and subtracts the hours from the date.

If no Date object is provided to the function, it uses the current date.

The getHours() method returns a number between 0 and 23 that represents the hour for the given date according to local time.

The setHours() method takes a number representing the hours as a parameter and sets the value for the date.

The JavaScript Date object automatically takes care of adjusting the day of the month, the month and the year, if subtracting X hours from the date pushes us into the previous day, month or year.

const date = new Date('2022-04-27T01:30:10.820'); date.setHours(date.getHours() - 3); console.log(date); // 👉️ Tue Apr 26 2022 22:30:10

Subtracting 3 hours from the date automatically adjusted the day of the month in the example.

Note that the setHours method mutates the Date object it was called on. If you don't want to change the Date in place, create a copy before calling the method.
function subtractHours(numOfHours, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setHours(dateCopy.getHours() - numOfHours); return dateCopy; } const date = new Date('2022-04-27T08:30:10.820'); const result = subtractHours(4, date); console.log(result); // 👉️ Wed Apr 27 2022 04:30:10 console.log(date); // 👉️ Wed Apr 27 2022 08:30:10 (didn't change original)

The getTime method returns the number of milliseconds elapsed between 1st of January, 1970 00:00:00 and the given date.

We used the timestamp to create a copy of the Date object, so we don't mutate it in place when calling the setHours 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.