Open In App

JavaScript Adding days in milliseconds to Date object

Last Updated : 20 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a date, the task is to add days in milliseconds to it using JavaScript. To add days in milliseconds to date objects in JavaScript, some methods are used which are listed below:

JavaScript getMilliseconds() Method: This method returns the milliseconds (from 0 to 999) of the provided date and time. 

Syntax:

Date.getMilliseconds()

Parameters: This method does not accept any parameters.

Return value: It returns a number, from 0 to 009, representing the milliseconds.

JavaScript setMilliseconds() Method: This method sets the milliseconds of a date object. 

Syntax:

Date.setMilliseconds(millisec)

Parameters:

  • millisec: This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970 

Return Value: It returns the new i.e updated millisecond which is set by the setMilliseconds() 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 sets the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970.

Syntax:

Date.setTime(millisec)

Parameters:

  • millisec: This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970 

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

Example 1: This example added 1 day in milliseconds to the variable today by using setTime() and getTime() methods.

Javascript




let today = new Date();
console.log("Date = " + today);
 
Date.prototype.addMillisecs = function (d) {
    this.setTime(this.getTime() + (d));
    return this;
}
 
let a = new Date();
let d = 1;
a.addMillisecs(d * 24 * 60 * 60 * 1000);
 
console.log(a);


Output

Date = Tue Jun 13 2023 20:33:11 GMT+0530 (India Standard Time)
Date Wed Jun 14 2023 20:33:11 GMT+0530 (India Standard Time)

Example 2: This example added 5 days in milliseconds to the variable today by using setMilliseconds() and getMilliseconds() methods.

Javascript




let today = new Date();
console.log("Date = " + today);
 
Date.prototype.addMillisecs= function(s) {
    this.setMilliseconds(this.getMilliseconds()+s);
    return this;
}
 
let a = new Date();
let d = 5;
a.addMillisecs(d * 24 * 60 * 60 * 1000);
 
console.log(a);


Output

Date = Tue Jun 13 2023 20:35:02 GMT+0530 (India Standard Time)
Date Sun Jun 18 2023 20:35:02 GMT+0530 (India Standard Time)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads