[javascript] Add 10 seconds to a Date

How can I add 10 seconds to a JavaScript date object?

Something like this:

var timeObject = new Date()     
var seconds = timeObject.getSeconds() + 10;
timeObject = timeObject + seconds;

This question is related to javascript

The answer is


  1. you can use setSeconds method by getting seconds from today and just adding 10 seconds in it

    var today = new Date();
    today.setSeconds(today.getSeconds() + 10);
    
  2. You can add 10 *1000 milliseconds to the new date:

    var today = new Date(); 
    today = new Date(today.getTime() + 1000*10);
    
  3. You can use setTime:

    today.setTime(now.getTime() + 10000)
    

Try this way.

Date.prototype.addSeconds = function(seconds) {
  var copiedDate = new Date(this.getTime());
  return new Date(copiedDate.getTime() + seconds * 1000);
}

Just call and assign new Date().addSeconds(10)


Try this

a = new Date();
a.setSeconds(a.getSeconds() + 10);

timeObject.setSeconds(timeObject.getSeconds() + 10)

The Date() object in javascript is not that smart really.

If you just focus on adding seconds it seems to handle things smoothly but if you try to add X number of seconds then add X number of minute and hours, etc, to the same Date object you end up in trouble. So I simply fell back to only using the setSeconds() method and converting my data into seconds (which worked fine).

If anyone can demonstrate adding time to a global Date() object using all the set methods and have the final time come out correctly I would like to see it but I get the sense that one set method is to be used at a time on a given Date() object and mixing them leads to a mess.

var vTime = new Date();

var iSecondsToAdd = ( iSeconds + (iMinutes * 60) + (iHours * 3600) + (iDays * 86400) );

vTime.setSeconds(iSecondsToAdd);

Here is some more documentation that may help:


Just for the performance maniacs among us.

getTime

var d = new Date('2014-01-01 10:11:55');
d = new Date(d.getTime() + 10000);

5,196,949 Ops/sec, fastest


setSeconds

var d = new Date('2014-01-01 10:11:55');
d.setSeconds(d.getSeconds() + 10);

2,936,604 Ops/sec, 43% slower


moment.js

var d = new moment('2014-01-01 10:11:55');
d = d.add(10, 'seconds');

22,549 Ops/sec, 100% slower


So maybe its the least human readable (not that bad) but the fastest way of going :)

jspref online tests


// let timeObject = new Date();
// let milliseconds= 10 * 1000; // 10 seconds = 10000 milliseconds
timeObject = new Date(timeObject.getTime() + milliseconds);

const timeObject = new Date(); 
timeObject = new Date(timeObject.getTime() + 1000 * 10);
console.log(timeObject);

Also please refer: How to add 30 minutes to a JavaScript Date object?


I have a couple of new variants

  1. var t = new Date(Date.now() + 10000);
  2. var t = new Date(+new Date() + 10000);