JavaScript Date getSeconds()
Syntax & Examples
Date.getSeconds() method
The getSeconds() method of the Date object in JavaScript returns the seconds (0 – 59) in the specified date according to local time.
Syntax of Date.getSeconds()
The syntax of Date.getSeconds() method is:
getSeconds()This getSeconds() method of Date returns the seconds (0 – 59) in the specified date according to local time.
Return Type
Date.getSeconds() returns value of type Number.
✐ Examples
1 Using getSeconds() to get the seconds of a specific date
In JavaScript, we can use the getSeconds() method to get the seconds from a Date object.
For example,
- We create a new Date object
daterepresenting January 15, 2021, at 15:30:45. - We use the
getSeconds()method to get the seconds fromdate. - The seconds are stored in the variable
seconds. - We log
secondsto the console usingconsole.log()method.
JavaScript Program
const date = new Date('2021-01-15T15:30:45');
const seconds = date.getSeconds();
console.log(seconds);Output
45
2 Using getSeconds() with the current date
In JavaScript, we can use the getSeconds() method to get the current seconds from the current date.
For example,
- We create a new Date object
nowrepresenting the current date and time. - We use the
getSeconds()method to get the current seconds fromnow. - The current seconds are stored in the variable
currentSeconds. - We log
currentSecondsto the console usingconsole.log()method.
JavaScript Program
const now = new Date();
const currentSeconds = now.getSeconds();
console.log(currentSeconds);Output
30
3 Using getSeconds() with a specific date in the past
In JavaScript, we can use the getSeconds() method to get the seconds from a specific date in the past.
For example,
- We create a new Date object
pastDaterepresenting July 4, 1776, at 12:00:30. - We use the
getSeconds()method to get the seconds frompastDate. - The seconds are stored in the variable
pastSeconds. - We log
pastSecondsto the console usingconsole.log()method.
JavaScript Program
const pastDate = new Date('1776-07-04T12:00:30');
const pastSeconds = pastDate.getSeconds();
console.log(pastSeconds);Output
30
Summary
In this JavaScript tutorial, we learned about getSeconds() method of Date: the syntax and few working examples with output and detailed explanation for each example.