# How to add seconds to a date in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 10, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-date-add-seconds

> Learn how to use the getSeconds() and setSeconds() methods of the date object to add seconds to date in JavaScript.

To add seconds to date in JavaScript:

1. Use the `getSeconds()` method to get the seconds of the given date.
2. Use the `setSeconds()` method by passing the result returned by `getSeconds()` plus the number of seconds you want to add.
3. The `setSeconds()` method sets the value on the given date.

Here is an example that adds 10 seconds to the current date in JavaScript:

```javascript
const today = new Date()
today.setSeconds(today.getSeconds() + 10)

console.log(today)
// Sat Sep 10 2022 22:47:41 GMT+0500 (Pakistan Standard Time)
```

The `getSeconds()` method returns a number between `0` and `59`, denoting the number of seconds of the given date.

The `setSeconds()` method takes a number as input representing the number of seconds and sets the value on the date.

The above methods also take care of the situation where adding a specific number of seconds to date results in the next day, month, or year:

```javascript
const date = new Date('2022-09-10T23:33:45.900Z')
date.setSeconds(date.getSeconds() + 30)

console.log(date.toUTCString())
// Sat, 10 Sep 2022 23:34:15 GMT
```

If you often need to add seconds to date, just create a reusable function that takes the number of seconds as a parameter and adds them to the current date:

```javascript
Date.prototype.addSeconds = function (secs) {
  const date = new Date(this.valueOf())
  date.setSeconds(date.getSeconds() + secs)
  return date
}

const date = new Date('2022-09-10T16:23:45.900Z')

// Add 45 Seconds
const result = date.addSeconds(45)

console.log(result.toUTCString())
// Sat, 10 Sep 2022 16:24:30 GMT
```

In the above example, we added a function called `addSeconds()` to the `Date` object [prototype](https://attacomsian.com/blog/objects-prototypes-classes-javascript#prototypes). This function will be available to all instances of `Date` for adding seconds to date.
