JavaScript Date setSeconds() Method



The JavaScript Date.setSeconds() method is used to set the "seconds" component of a date object. This method affects only the seconds part of the date, leaving other components (such as hours, minutes, milliseconds) unchanged. Additionally, we can modify the "milliseconds" of the date object.

The return value of this method will be an updated timestamp of the Date object, which reflects the changes made by modifying the seconds component. If the value passed is greater than 59 or less than 0, it will automatically adjust the other components accordingly.

Syntax

Following is the syntax of JavaScript Date setSeconds() method −

setSeconds(secondsValue, millisecondsValue);

Parameters

This method accepts two parameters. The same is described below −

  • secondsValue − An integer representing the seconds (0 to 59).
    • If -1 is provided, it will result in the last second of the previous minute.
    • If 60 is provided, it will result in the first second of the next minute.
  • millisecondsValue (optional) − An integer representing the milliseconds (0 to 999).
    • If -1 is provided, it will result in the last millisecond of the previous second.
    • If 1000 is provided, it will result in the first millisecond of the next second.

Return value

This method returns the timestamp representing the adjusted date after setting the new month.

Example 1

In the following example, we are using the JavaScript Date setSeconds() method to set the "seconds" of the current Date to 30 −

<html>
<body>
<script>
   const currentDate = new Date();
   currentDate.setSeconds(30);

   document.write(currentDate);
</script>
</body>
</html>

Output

If we execute the above program, the seconds will be set to 30.

Example 2

Here, we are adding 15 seconds to the specified date −

<html>
<body>
<script>
   const currentDate = new Date("2023-12-25 18:30:10");
   currentDate.setSeconds(currentDate.getSeconds() + 15);

   document.write(currentDate);
</script>
</body>
</html>

Output

It will return a timestamp as "Mon Dec 25 2023 18:30:25 GMT+0530 (India Standard Time)".

Example 3

If we provide "-1" for secondsValue, this method will gives the last second of the previous minute −

<html>
<body>
<script>
   const currentDate = new Date("2023-12-25 18:30:10");
   currentDate.setSeconds(-1);

   document.write(currentDate);
</script>
</body>
</html>

Output

It will return a timestamp as "Mon Dec 25 2023 18:29:59 GMT+0530 (India Standard Time)".

Example 4

If we provide "60" for secondsValue, this method will gives the first second of the next minute −

<html>
<body>
<script>
   const currentDate = new Date("2023-12-25 18:30:10");
   currentDate.setSeconds(60);

   document.write(currentDate);
</script>
</body>
</html>

Output

It will return a timestamp as "Mon Dec 25 2023 18:31:00 GMT+0530 (India Standard Time)".

Advertisements