Open In App

JavaScript Increment a given date

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

Given a date, the task is to increment the given date by using JavaScript. To increment a date in JavaScript, we’re going to discuss a few methods, some of these are:

JavaScript getDate() method: This method returns the day of the month (from 1 to 31) for the defined date.

 Syntax:

Date.getDate()

Parameters: This method does not accept any parameters.

Return value: It returns a number, from 1 to 31, denoting the day of the month.

JavaScript setDate() method This method sets the day of the month to the date object.

Syntax:

Date.setDate(day)

Parameters: This method accepts single parameter day which is required. It specifies the integer defining the day of the month. Values expected are 1-31 but less than 1 and greater than 31 values are used appropriately for the previous and next month.

Return value: This method return the number of milliseconds between the date object and midnight of January 1, 1970.

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: This method accepts single parameter millisec which is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970.

Return Value: The setTime() Function returns milliseconds between January 1 1970 and the time you passed in the parameter.

Example 1:This example increments 1 day to the current date by using setDate() and getDate() methods.

Javascript




let today = new Date();
console.log("Today's date = " + today);
 
let tomorrow = new Date();
tomorrow.setDate(today.getDate() + 1);
 
console.log(tomorrow);


Output

Today's date = Tue Jun 13 2023 20:02:43 GMT+0530 (India Standard Time)
Date Wed Jun 14 2023 20:02:43 GMT+0530 (India Standard Time)

Example 2:This example increments 10 day to the current date by using setTime() and getTime() methods.

Javascript




let today = new Date();
let days = 10;
 
console.log("Today's date = " + today);
 
let tomorrow = new Date();
tomorrow.setTime(today.getTime() + days * 86400000);
 
console.log(tomorrow);


 Output

Today's date = Tue Jun 13 2023 20:11:13 GMT+0530 (India Standard Time)
Date Fri Jun 23 2023 20:11:13 GMT+0530 (India Standard Time)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads