JavaScript date.setSeconds(seconds, milliseconds) method
The date.setSeconds(seconds, milliseconds)
method in JavaScript is used to set the seconds for a specified Date
object according to local time. Optionally, you can also specify the milliseconds.
Syntax:
Parameters:
- seconds: An integer between
0
and59
, representing the seconds value to set. - milliseconds (optional): An integer between
0
and999
, representing the milliseconds value to set. If not provided, the current milliseconds value of theDate
object is used.
Returns:
- The number of milliseconds since January 1, 1970, 00:00:00 UTC, after updating the
Date
object.
Example 1: Setting the Seconds Only
Output:
Explanation:
- The seconds are updated to
45
, but the other time components (hours, minutes) remain unchanged.
Example 2: Setting Both Seconds and Milliseconds
Output:
Explanation:
- The seconds are set to
50
, and the milliseconds are updated to250
. All other date and time parts (like minutes and hours) remain unchanged.
Example 3: Handling Overflow of Seconds
If the value of seconds
exceeds 59
, it will roll over to the next minute (or hour, day, etc., if needed).
Output:
Explanation:
- Since
75
seconds exceeds59
, it rolls over to the next minute, adding 1 minute to the time (from 10:15:30 to 10:16:15).
Example 4: Handling Negative Seconds
You can also pass negative values for seconds
, and the method will adjust the time accordingly.
Output:
Explanation:
- Setting the seconds to
-15
rolls back the time by 15 seconds into the previous minute (from 10:15:30 to 10:14:45).
Example 5: Setting Both Seconds and Milliseconds with Overflow
If both seconds
and milliseconds
exceed their normal range, JavaScript will adjust the time accordingly.
Output:
Explanation:
65
seconds adds 1 minute and 5 seconds, and1100
milliseconds rolls over to100
milliseconds. The final time becomes10:16:06.100
.
Example 6: Retaining Existing Milliseconds
If you only specify the seconds
parameter, the milliseconds
will remain unchanged.
Output:
Explanation:
- The seconds are set to
40
, and the existing milliseconds500
are retained.
Summary:
date.setSeconds(seconds[, milliseconds])
allows you to update the seconds and optionally the milliseconds of aDate
object.- JavaScript automatically handles overflow in seconds and milliseconds, adjusting other time components (minutes, hours) as needed.
- If only the
seconds
are provided, the milliseconds remain unchanged.