Open In App

JavaScript Adding minutes to Date object

Given a date and the task is to add minutes to it using JavaScript. To add minutes to the date object, some methods are used which are listed below:

JavaScript getMinutes() Method: This method returns the Minutes (from 0 to 59) of the provided date and time. 



Syntax:

Date.getMinutes()

Parameters: This method does not accept any parameters.



Return value: It returns a number, from 0 to 59, representing the minutes.

JavaScript setMinutes() Method: This method set the minutes of a date object. This method can also be used to set the seconds and milliseconds. 

Syntax:

Date.setMinutes(min, sec, millisec)

Parameters:

Return Value: It returns the new date with updated minute which is set by setMinutes() method.

JavaScript getTime() method: This method returns the number of milliseconds between midnight of January 1, 1970, and the specified date. 

Syntax:

Date.getTime()

Parameters: This method does not accept any parameters.

Return value: It returns a number, representing the number of milliseconds since midnight January 1, 1970.

JavaScript setTime() method: This method set the date and time by adding/subtracting a defined number of milliseconds to/from midnight January 1, 1970.

Syntax:

Date.setTime(millisec)

Parameters: 

Return value: It returns, representing the number of milliseconds between the date object and midnight January 1 1970. 

Example 1: This example added 4 minutes to the variable today by using setTime() and getTime() methods. 




let today = new Date();
console.log("Date = " + today);
 
Date.prototype.addMins = function (m) {
    this.setTime(this.getTime() + (m * 60 * 1000));
    return this;
}
 
let a = new Date();
a.addMins(4);
 
console.log(a);

Output

Date = Tue Jun 13 2023 20:16:29 GMT+0530 (India Standard Time)
Date Tue Jun 13 2023 20:20:29 GMT+0530 (India Standard Time)

Example 2: This example adds 6 minutes to the variable today by using setMinutes() and getMinutes() methods.




let today = new Date();
console.log("Date = " + today);
 
Date.prototype.addMinutes = function (m) {
    this.setMinutes(this.getMinutes() + m);
    return this;
}
 
let a = new Date();
a.addMinutes(6);
 
console.log(a);

Output:

Date = Tue Jun 13 2023 20:18:07 GMT+0530 (India Standard Time)
Date Tue Jun 13 2023 20:24:07 GMT+0530 (India Standard Time)

Article Tags :