JavaScript Date setDate()

Posted by

Method

JavaScript Date setDate() Method

The JavaScript Date setDate() method is used to set the day of the month for a specified date according to local time. The setDate() method takes a parameter which is an integer between 1 and 31, representing the day of the month.

Syntax

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]


dateObj.setDate(dayValue)

[/dm_code_snippet]

Parameters

The setDate() method takes one parameter:

  • dayValue – An integer between 1 and 31, representing the day of the month.

Return Value

The setDate() method returns the number of milliseconds since January 1, 1970 00:00:00 UTC corresponding to the updated date.

Browser Support

The setDate() method is supported in all major browsers.

Example

The following example shows the use of the setDate() method:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]


// Create a new date object
var d = new Date();
 
// Set the day of the month to 15
d.setDate(15);
 
// Display the updated date
document.write(d);

[/dm_code_snippet]

The above code will output the following:

Mon Aug 24 2020 15:00:00 GMT+0200 (Central European Summer Time)

More Examples

The following example shows the use of the setDate() method to set the day of the month to the last day of the current month:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]


// Create a new date object
var d = new Date();
 
// Get the last day of the current month
var lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
 
// Set the day of the month to the last day of the current month
d.setDate(lastDay);
 
// Display the updated date
document.write(d);

[/dm_code_snippet]

The above code will output the following:

Mon Aug 31 2020 15:00:00 GMT+0200 (Central European Summer Time)