Subtract Minutes from a Date in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 21, 2022

banner

Photo from Unsplash

Subtract Minutes from a Date in JavaScript #

To subtract minutes to a date:

  1. Use the getMinutes() method to get the minutes of the given date.
  2. Use the setMinutes() method to set the minutes for the date.
  3. The setMinutes method takes the minutes as a parameter and sets the value for the date.
index.js
function subtractMinutes(numOfMinutes, date = new Date()) { date.setMinutes(date.getMinutes() - numOfMinutes); return date; } // 👇️ Subtract 15 minutes from current Date const result = subtractMinutes(15); // 👇️ Subtract 20 minutes from another date const date = new Date('2022-06-24T08:35:10.820'); // 👇️ Fri Jun 24 2022 08:15:10 console.log(subtractMinutes(20, date));

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

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

The getMinutes() method returns a number between 0 and 59 that represents the minutes in the given date.

The setMinutes() method takes a number representing the minutes as a parameter and sets the value on the date.

The JavaScript Date object automatically takes care of adjusting the hours, days, months and years if subtracting X minutes from the date changes their values.

index.js
const date = new Date('2022-06-24T00:15:10.820'); date.setMinutes(date.getMinutes() - 35); console.log(date); // 👉️ Thu Jun 23 2022 23:40:10

The example shows how subtracting 35 minutes from the date automatically adjusts the hour and day of the month on the Date object.

Note that the setMinutes 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 subtractMinutes(numOfMinutes, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setMinutes(dateCopy.getMinutes() - numOfMinutes); return dateCopy; } const date = new Date('2022-06-24T07:35:10.820'); const result = subtractMinutes(15, date); console.log(result); // 👉️ Fri Jun 24 2022 07:20:10 console.log(date); // 👉️ Fri Jun 24 2022 07:35: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 setMinutes 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.