How to Add Minutes to a Date in JavaScript

Learn multiple ways to easily add minutes to a Date object in JavaScript.

Tari Ibaba
2 min readJul 5, 2022

1. Date setMinutes() and getMinutes() Methods

To add minutes to a Date in JavaScript, call the getMinutes() method on the Date to get the minutes, then call the setMinutes() method on the Date, passing the sum of the Date minutes and the minutes to add.

function addMinutes(date, minutes) {
date.setMinutes(date.getMinutes() + minutes);
return date;
}
const date = new Date('2022-05-15T00:00:00.000Z');const newDate = addMinutes(date, 10);// 2022-05-15T00:10:00.000Z
console.log(newDate);

Our addMinutes() function takes a Date and the number of minutes to add as arguments, and returns the same Date with the newly added minutes.

The Date getMinutes() method returns a number between 0 and 59 that represents the minutes of the Date.

The Date setMinutes() method takes a number representing minutes and set the minutes of the Date to that number.

If the minutes you specify would change the hour, day, month, or year of the Date, setMinutes() automatically updates the Date information to reflect this.

const date = new Date('2022-05-15T00:00:00.000Z');date.setMinutes(date.getMinutes() + 150);
console.log(date);

In this example, passing 150 to setMinutes() increments the Date hours by 2 (120 minutes) and set the minutes to 30.

Avoiding Side Effects

The setMinutes() method mutates the Date object it is called on. This introduces a side effect into our addMinutes() function. To avoid modifying the passed Date and create a pure function, make a copy of the Date and call setMinutes() on this copy, instead of the original:

function addMinutes(date, minutes) {
const dateCopy = new Date(date);
dateCopy.setMinutes(date.getMinutes() + minutes);
return dateCopy;
}
const date = new Date('2022-05-15T00:00:00.000Z');const newDate = addMinutes(date, 10);console.log(newDate); // 2022-05-15T00:10:00.000Z// Original not modified
console.log(date); // 2022-05-15T00:00:00.000Z

Tip

Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about. This makes it a good practice to limit the number of side-effects in your programs.

2. date-fns addMinutes()

Alternatively, you can use the pure addMinutes() function from the date-fns NPM package to quickly add minutes to a Date.

import { addMinutes } from 'date-fns';const date = new Date('2022-05-15T00:00:00.000Z');
const newDate = addMinutes(date, 10);
console.log(newDate); // 2022-05-15T00:10:00.000Z// Original not modified.
console.log(date); // 2022-05-15T00:00:00.000Z

Updated at: codingbeautydev.com

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Sign up and receive a free copy immediately.

--

--

Tari Ibaba

I help you gain the coding knowledge and skills to build the life you love.