To add minutes to date in JavaScript:
- Use the
getMinutes()
method to get the minutes of the given date. - Use the
setMinutes()
method by passing the result returned bygetMinutes()
plus the number of minutes you want to add. - The
setMinutes()
method sets the value on the given date.
Here is an example that adds 30 minutes to the current date in JavaScript:
const today = new Date()
today.setMinutes(today.getMinutes() + 30)
console.log(today)
// Sat Sep 10 2022 22:47:41 GMT+0500 (Pakistan Standard Time)
The getMinutes()
method returns a number between 0
and 59
, denoting the number of minutes on the given date.
The setMinutes()
method takes a number as input representing the number of minutes and sets the value on the date.
The above methods also take care of the situation where adding a specific number of minutes to date results in the next day, month, or year:
const date = new Date('2022-09-10T23:33:23.900Z')
date.setMinutes(date.getMinutes() + 30)
console.log(date.toUTCString())
// Sun, 11 Sep 2022 00:03:23 GMT
If you frequently need to add minutes to date, just create a reusable function that takes the number of minutes as a parameter and adds them to the current date:
Date.prototype.addMinutes = function (mins) {
const date = new Date(this.valueOf())
date.setMinutes(date.getMinutes() + mins)
return date
}
const date = new Date('2022-09-10T16:23:23.900Z')
// Add 45 Minutes
const result = date.addMinutes(45)
console.log(result.toUTCString())
// Sat, 10 Sep 2022 17:08:23 GMT
In the above example, we added a function called addMinutes()
to the Date
object prototype. This function will be available to all instances of Date
for adding minutes to date.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.