• JavaScript Video Tutorials

JavaScript Date getSeconds() Method



In JavaScript, the Date.getSeconds() method is used to get the seconds component of a specified date and time, based on the local time zone. The return value will be an integer between (0 to 59) specifies seconds of a date.

If we provided Date object is invalid, this method returns Not a Number (NaN) as result.

Syntax

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

getSeconds();

This method does not accept any parameters.

Return Value

This method returns an integer representing the seconds component of the time portion of the Date object.

Example 1

In the following example, we are demonstrating the basic usage of JavaScript Date getSeconds() method −

<html>
<body>
<script>
   const currentDate = new Date();
   const seconds = currentDate.getSeconds();

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

Output

The above program returns the seconds of a date according to the local time.

Example 2

Here, we are fetching the seconds component from the provided date using the getSeconds() method.

<html>
<body>
<script>
   const specificDate = new Date('December 25, 2023 10:30:45');
   const seconds = specificDate.getSeconds();

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

Output

The above program returns integer 45 as seconds value.

Example 3

Here, we have set a "setInterval" which will print the seconds from local time for every 2 seconds.

<html>
<body>
<script>
   function printSeconds() {
      const currentDate = new Date();
      const seconds = currentDate.getSeconds();
      document.write(seconds + "<br>");
   }

   setInterval(printSeconds, 2000);
</script>
</body>
</html>

Output

As we can see the output, the seconds are printing for every 2 seconds.

Advertisements