How to add seconds to a date object in JavaScript
Hi coders, this is a JavaScript tutorial to show you how to add seconds to date in JavaScript. You will learn how to add seconds to date object in JavaScript. In my previous tutorials, I have shown you very closely related tutorials with this one.
How to add hours to a JavaScript Date object?
How to add minutes to date in the JavaScript date object
To add seconds to date in JavaScript we need to use these following methods:
- getSeconds()
- setSeconds()
How to compare two dates in JavaScript
Add Seconds To Date in JavaScript
As an example, we are going to add 15 seconds to a date in the below example.
<!DOCTYPE html>
<html>
<head>
<title>Your Title Goes Here</title>
</head>
<body>
<script type="text/javascript">
var date1 = new Date("October 24, 2018 02:20:15");
date1.setSeconds(date1.getSeconds()+15);
document.write(date1);
</script>
</body>
</html>
Here we have used Date object and two methods: setSeconds() and getSeconds()
The output of this Script:
Wed Oct 24 2018 02:20:30 GMT+0530 (India Standard Time)
I have added 15 seconds with this below line:
date1.setSeconds(date1.getSeconds()+15);
getSeconds() method will fetch the seconds from the Date object. Next, I have used +15 to add an extra 15 seconds to it.
I hope this tutorial is useful to you. Feel free to comment in the below comment section. Happy coding
Leave a Reply