Add 10 seconds to a Javascript date object timeObject

Add 10 seconds to a Javascript date object timeObject

How can I add 10 seconds to a javascript date object timeObject.
Something like this I think..
var timeObject = new Date()
var seconds = timeObject.getSeconds() + 10;
timeObject = timeObject + seconds;

Solutions/Answers:

Solution 1:

There’s a setSeconds method as well:

var t = new Date();
t.setSeconds(t.getSeconds() + 10);

For a list of the other Date functions, you should check out MDN


setSeconds will correctly handle wrap-around cases:

var d;
d = new Date('2014-01-01 10:11:55');
alert(d.getMinutes() + ':' + d.getSeconds()); //11:55
d.setSeconds(d.getSeconds() + 10);
alert(d.getMinutes() + ':0' + d.getSeconds()); //12:05

Solution 2:

// var timeObject = new Date();

new Date(timeObject.getTime() + 10000);

Solution 3:

var 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?

Solution 4:

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

Related:  is there a mongoose connect error callback

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

jspref online tests

Solution 5:

Try this

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

Solution 6:

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