JavaScript Add Seconds to Date
Managing time-related functionalities in JavaScript often involves manipulating dates by adding or subtracting specific time units, such as seconds.
Adding seconds to a Date object is crucial for various applications, from countdown timers ⏳ to scheduling events 📅.
- Using setSeconds() Method
- Using getTime() and setTime() Methods
- Using the Date Constructor
- Using Libraries like date-fns or moment.js
- Conclusion
Table of Contents
1. Using setSeconds() Method
The setSeconds() method of the Date object allows us to directly modify the seconds ⏲️.
For this, you need to pass current second + the number of seconds you want to add to the setSeconds()
method.
Let's add 20 seconds to the current time.
Example
let date = new Date();
console.log(date);
// ⏲️ Adding 20 seconds
date.setSeconds(date.getSeconds() + 20);
console.log(date);
Here, we have used the getSeconds() method to get the current seconds and then added 20 seconds to it.
2. Using getTime() and setTime() Methods
The getTime() method returns time in milliseconds since 1 January 1970 UTC, and the setTime() method sets the time by taking the time in milliseconds.
We can use combination of these two methods to add seconds to a Date object. Get the current time in milliseconds, add the number of seconds you want to add in milliseconds, and then set the time using the setTime()
method.
Example
let date = new Date();
console.log(date);
// ⏲️ Adding 20 seconds
date.setTime(date.getTime() + (20 * 1000));
console.log(date);
3. Using the Date Constructor
The Date() constructor can create a Date object by taking the time in in various formats, including milliseconds.
We can use same approach as above and can add seconds to the time.
Example
let date = new Date();
console.log(date);
// ⏲️ Adding 20 seconds
date = new Date(date.getTime() + (20 * 1000));
console.log(date);
4. Using Libraries like date-fns or moment.js
Libraries such as date-fns or moment.js offer specialized functions for simplified date and time manipulations.
Using date-fns
The addSeconds() function is a direct function provided by the date-fns library to add seconds.
let { addSeconds } = require('date-fns');
let date = new Date();
console.log(date);
// ⏲️ Adding 20 seconds
date = addSeconds(date, 20);
console.log(date);
Using moment.js
The add() function can add different time units to a moment object. To add 20 seconds, we can use the add() function as add(20, 'seconds')
.
let moment = require('moment');
let date = moment();
console.log(date);
// ⏲️ Adding 20 seconds
date = date.add(20, 'seconds');
console.log(date);
Conclusion
Adding seconds to a JavaScript Date can be performed in various ways, such as setSeconds() method, getTime() and setTime() methods, or third-party libraries like date-fns or moment.js.