JavaScript date.setMilliseconds(milliseconds) method


The date.setMilliseconds(milliseconds) method in JavaScript is used to set the milliseconds for a specified Date object according to local time. This method modifies the original Date object and can be used to adjust the time down to the millisecond level.

Syntax:

date.setMilliseconds(milliseconds);

Parameters:

  • milliseconds: An integer representing the milliseconds (from 0 to 999).

Returns:

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

Example 1: Setting Milliseconds

const date = new Date('2024-10-22T12:30:45.123Z'); // October 22, 2024, 12:30:45.123 date.setMilliseconds(456); // Change milliseconds to 456 console.log(date);

Output:

2024-10-22T12:30:45.456Z

Explanation:

  • The original date of October 22, 2024, 12:30:45.123 is updated to 12:30:45.456.

Example 2: Setting Milliseconds with Current Time

const date = new Date(); // Current date and time console.log("Before:", date); // Log current time date.setMilliseconds(999); // Set milliseconds to 999 console.log("After:", date); // Log updated time

Output:

Before: 2024-10-22T12:30:45.123Z After: 2024-10-22T12:30:45.999Z

Explanation:

  • The setMilliseconds(999) method updates the milliseconds of the current date to 999.

Example 3: Handling Time Adjustments

const date = new Date('2024-10-22T12:30:59.950Z'); // October 22, 2024, 12:30:59.950 date.setMilliseconds(1000); // Try to set milliseconds to 1000 console.log(date);

Output:

2024-10-22T12:31:00.000Z

Explanation:

  • When setting the milliseconds to 1000, the Date object automatically rolls over to the next second, resulting in 12:31:00.000.

Summary:

  • date.setMilliseconds(milliseconds) allows you to set the milliseconds for a Date object, affecting the time representation.
  • It modifies the original Date object and can trigger automatic adjustments if the specified milliseconds cause the time to exceed normal bounds (e.g., rolling over to the next second).