JavaScript Date setSeconds()

Posted by

Method

JavaScript Date setSeconds() Method

The JavaScript setSeconds() method is used to set the seconds for a specified date according to local time. The setSeconds() method sets the seconds for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC.

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.setSeconds(secValue[, msValue])

[/dm_code_snippet]

Parameters:
secValue – An integer between 0 and 59, representing the seconds.
msValue – An integer between 0 and 999, representing the milliseconds.

Return Value:
An integer representing the number of milliseconds since January 1, 1970 00:00:00 UTC, with the newly set seconds.

Example:

[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”]

var d = new Date();
d.setSeconds(59);
document.write(d);

[/dm_code_snippet]

Output:
Wed Dec 31 1969 19:00:59 GMT-0500 (Eastern Standard Time)

The above example sets the seconds to 59 for the specified date according to the local time. The output shows the date/time after setting the seconds.

More Examples

Example 1: Set the seconds with milliseconds.

[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”]

var d = new Date();
d.setSeconds(59, 999);
document.write(d);

[/dm_code_snippet]

Output:
Wed Dec 31 1969 19:00:59 GMT-0500 (Eastern Standard Time)

Example 2: Set the seconds with wrong milliseconds.

[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”]

var d = new Date();
d.setSeconds(59, 1000);
document.write(d);

[/dm_code_snippet]

Output:
Wed Dec 31 1969 19:01:00 GMT-0500 (Eastern Standard Time)

In the above example, the milliseconds are set to 1000 which is greater than the maximum value for milliseconds. Therefore, the output shows the date/time with 1 second added to it.

Browser Support

The setSeconds() method is supported by all major browsers including Chrome, Firefox, Internet Explorer and Safari.