Add 10 Seconds To A Date


Answer :

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


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

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


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable