JavaScript setDate(day) method


The date.setDate(day) method in JavaScript sets the day of the month for a specified Date object according to local time. It modifies the original Date object and can handle month changes if the specified day exceeds the number of days in the month.

Syntax:

date.setDate(day);

Parameters:

  • day: An integer representing the day of the month (from 1 to 31).

Returns:

  • The number of milliseconds since January 1, 1970, 00:00:00 UTC, representing the updated Date object.

Example 1: Setting the Day of the Month

const date = new Date('2024-10-22'); // October 22, 2024 date.setDate(15); // Set to the 15th day of the month console.log(date);

Output:

2024-10-15T00:00:00.000Z

Explanation:

  • The original date of October 22, 2024, is changed to October 15, 2024, as specified by setDate(15).

Example 2: Setting the Day Beyond Month Length

const date = new Date('2024-01-30'); // January 30, 2024 date.setDate(31); // Set to the 31st day of January console.log(date);

Output:

2024-01-31T00:00:00.000Z

Explanation:

  • The date is successfully changed to January 31, 2024.

Example 3: Setting the Day to a Value Exceeding Month Length

const date = new Date('2024-01-30'); // January 30, 2024 date.setDate(32); // Set to the 32nd day of January console.log(date);

Output:

2024-02-01T00:00:00.000Z

Explanation:

  • When trying to set the date to 32, JavaScript automatically adjusts the date to February 1, 2024, since January has only 31 days.

Example 4: Using Negative Values

const date = new Date('2024-03-01'); // March 1, 2024 date.setDate(-1); // Set to the last day of the previous month (February) console.log(date);

Output:

2024-02-29T00:00:00.000Z

Explanation:

  • Setting the date to -1 adjusts the date to the last day of February 2024 (a leap year), which is February 29.

Summary:

  • date.setDate(day) sets the day of the month for a Date object and can automatically handle month boundaries and leap years.
  • It modifies the original Date object and returns the timestamp in milliseconds since January 1, 1970, UTC. This makes it flexible for manipulating dates and managing different month lengths.