Add Seconds to a Date in Node.js and JavaScript

While building the queuing feature in the Supercharge framework, we wanted to enqueue jobs with a delay. You can delay a job by a given number of seconds. Internally, Supercharge stores a notBefore date with the added delay seconds.

This tutorial shows you how to add seconds to a date in Node.js and JavaScript.

Node.js Series Overview

Add Seconds to a Date

The following example uses a dateWith(delay) function illustrating how to add seconds to a date. First, create a new date representing “now”. Then, replace the seconds of the “now” date by adding the delay to the current time:

/**
 * Calculates the date with added `delay`.
 *
 * @param {Number} delay in seconds
 *
 * @returns {Date}
 */
dateWith (delay) {  
  const date = new Date()
  date.setSeconds(date.getSeconds() + delay)

  return date
}

The JavaScript runtime also handles delays with more than 59 seconds properly. For example, when adding a delay of 100 seconds, setSeconds() increments the minutes by 1 and seconds by 40.


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.