Borislav Hadzhiev
Last updated: Jan 21, 2022
Check out my new book
To add minutes to a date:
getMinutes()
method to get the minutes of the specific date.setMinutes()
method to set the minutes for the date.setMinutes
method takes the minutes as a parameter and sets the value
for the date.function addMinutes(numOfMinutes, date = new Date()) { date.setMinutes(date.getMinutes() + numOfMinutes); return date; } // 👇️ Add 10 minutes to current Date const result = addMinutes(10); // 👇️ Add 20 minutes to other Date const date = new Date('2022-03-14T09:25:30.820'); // 👇️ Mon Mar 14 2022 09:45:30 console.log(addMinutes(20, date));
We created a reusable function that takes the number of minutes and a Date
object and adds the minutes to 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 rolling over the
hours, days, months and years if adding X minutes to the date changes their
values.
const date = new Date('2022-03-14T23:25:30.820'); date.setMinutes(date.getMinutes() + 36); console.log(date); // 👉️ Tue Mar 15 2022 00:01:30
We added 36
minutes to the date, so the hour and the day of the month had to
be adjusted.
The Date
object would automatically take care of adjusting the month and year
as well.
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.function addMinutes(numOfMinutes, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setMinutes(dateCopy.getMinutes() + numOfMinutes); return dateCopy; } const date = new Date('2022-03-14T23:25:30.820'); const result = addMinutes(20, date); console.log(result); // 👉️ Mon Mar 14 2022 23:45:30 console.log(date); // 👉️ Mon Mar 14 2022 23:25:30 (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.
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.
You might see the setMinutes
method get called with 3
parameters. The
parameters the method takes are:
minutes
- a number representing the minutes.seconds
(optional) - a number representing the seconds.milliseconds
(optional) - a number between 0
and 999
that represents
the milliseconds.If you don't specify values for the seconds
and milliseconds
, the values
returned from the getSeconds()
and getMilliseconds()
methods are used.