389

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;
Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
george
  • 4,119
  • 3
  • 17
  • 18
  • 4
    Or if you want to do it via the constructor - new Date(new Date().getTime() + 10000) – John Strickler Oct 07 '11 at 13:27
  • 2
    Possible duplicate of [How to add 30 minutes to a JavaScript Date object?](https://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object) – Kip Sep 07 '17 at 20:34
  • you can also simply `new Date(+timeObject + seconds * 1000)` – dcts Oct 10 '20 at 15:54

13 Answers13

600

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
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • 5
    Beware, my Nodejs installation returns d.getSeconds() as a string. I had to change this to (+d.getSeconds()) The unary plus converts a string to a number. Perhaps a little more obvious would be 1*d.getSeconds() – tqwhite Nov 30 '16 at 21:41
  • 1
    @tqwhite, `typeof new Date().getSeconds()` returns `'number'` in node, so I think you may have other issues (unless you're on an outdated version of node or something). – zzzzBov Nov 30 '16 at 21:44
  • 5
    Try doing `d.setSeconds(d.getSeconds() - 92);` and you'll end up with 2'32" difference instead of 1'32". The solution with `new Date(d.getTime() - 92*1000);` works however ! – Rafalon Oct 16 '17 at 12:42
  • @Rafalon, [that doesn't appear to be the case](https://jsfiddle.net/6cwq8rm1/), please double check and provide a working example of the behavior you describe. – zzzzBov Oct 16 '17 at 13:48
  • @zzzzBov which browser do you use ? I was on IE11 when I noticed the difference, I'll doublecheck tomorrow – Rafalon Oct 16 '17 at 16:22
  • 8
    Relying on undocumented behavior (that setSeconds(70) will increment minutes by one and set seconds to 10) seems like a generally bad practice. The (currently next) answers pointing to Date.getTime() + seem to be the intended and supported approach, and would be clear to most programmers coming from different languages without encyclopedic knowledge of the undocumented nuances of each particular JavaScript engine. – Tom Dibble Oct 16 '17 at 16:42
  • @TomDibble, wrt undocumented behavior: [ECMAScript specifies the behavior of `Date.prototype.setSeconds`](http://es5.github.io/#x15.9.5.30). Of course, I have linked to the ES5 spec, which has been superseded by later ECMAScript specifications, but the point still stands that the behavior should be considered documented, and any variations are likely implementation bugs. – zzzzBov Oct 16 '17 at 17:05
  • @Rafalon, I noticed some issues with my prior example for IE11, it didn't like the format I used in the `Date` declaration (and the use of `const`), so here's an [updated example](https://jsfiddle.net/rtd8vc6a/). – zzzzBov Oct 16 '17 at 17:23
  • 1
    An issue could occur with historical time zones, see comments underneath @Ron's answer: https://stackoverflow.com/a/17267937/198797. Possibly not a common scenario but an issue nonetheless. – tsemer Jan 04 '18 at 16:50
179
let timeObject = new Date();
const milliseconds = 10 * 1000; // 10 seconds = 10000 milliseconds
timeObject = new Date(timeObject.getTime() + milliseconds);
Spikolynn
  • 4,067
  • 2
  • 37
  • 44
4esn0k
  • 9,789
  • 7
  • 33
  • 40
  • 38
    ... and the reason you added 10000 is because Javascript dates work in milliseconds, i.e. 10000 = 10 * 1000 – psiphi75 Jun 17 '14 at 03:45
  • 1
    And the + before timeObject is needed because it casts timeObject to a number. So its like timeObject.getTime() in Ron's answer – James Jan 16 '15 at 13:58
  • 3
    Quick kinda-obvious tip: if you're adding seconds to the current date, you can shorten the code a little bit by using `Date.now()`. Example: `const timeObject = new Date(Date.now() + milliseconds);` – jaquinocode Mar 15 '22 at 16:33
  • 1
    Why are the first two lines commented? These should be uncommented for the code to work properly ☝ – Youp Bernoulli Aug 12 '22 at 11:39
104

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

Danpe
  • 18,668
  • 21
  • 96
  • 131
63
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?

A1rPun
  • 16,287
  • 7
  • 57
  • 90
Ron
  • 6,037
  • 4
  • 33
  • 52
  • 8
    of all the wrong answers here, this is the correct one. – Cory Mawhorter Feb 28 '14 at 22:07
  • Yes, this is the correct answer. Unfortunately Google is referring to this Question if searching for "javascript date add seconds" and the most voted answer is wrong. – Philipp Gächter Jun 23 '14 at 07:32
  • 2
    Can anybody please explain what the selected answer (currently from @zzzzBov) is doing wrong? It works for me. – tsemer Jul 21 '16 at 10:55
  • @tsemer I think that works. From MDN: If a parameter you specify is outside of the expected range, setSeconds() attempts to update the date information in the Date object accordingly. For example, if you use 100 for secondsValue, the minutes stored in the Date object will be incremented by 1, and 40 will be used for seconds. – Ron Aug 17 '16 at 11:18
  • Thanks Ron, but I'm not challenging if your answer works. I'm wondering why @CoryMawhorter wrote that the other answers are all wrong, and 4 others upvoted his comment. For me they both work, in which case it's a matter of taste. – tsemer Aug 19 '16 at 10:26
  • 1
    @tsemer, at the first glance, I thought zzzzBov's answer is not right, because I didn't think it will update the minute value if it is out of the range. But because of your "challenging", I reviewed the MDN, and confirmed that answer is definitely right. :) – Ron Aug 19 '16 at 11:15
  • @tsemer I'm not sure exactly, but IIRC it had something to do with differences in setSeconds implementations creating hidden problems. That may have changed, but `.getTime() + (1000 * seconds)` is a guaranteed-to-work way AFAIK. – Cory Mawhorter Aug 20 '16 at 17:05
  • Thanks @CoryMawhorter. If you ever come across those hidden problems I'm sure the community would appreciate it if you post them here :) – tsemer Aug 22 '16 at 11:15
  • 1
    @tsemer Try in a web browser with Historical TimeZones support (Internet Explorer 11,for example): Also set your system TimeZone to "Asia/Yekaterinburg": `var timestamp = Date.parse("2011-03-26T20:59:59.999Z"); var d = new Date(timestamp); d.setSeconds(d.getSeconds() + 10); console.log(d.getTime() - timestamp);` – 4esn0k Jul 25 '17 at 10:18
  • @tsemer i've been using the simpler techniques for ages now. it must've been vendor specific and short lived. ignore my previous comment ;] – Cory Mawhorter Jan 02 '18 at 16:10
  • @CoryMawhorter, good to know thank you :) however: @4esn0k, nice catch! This is indeed an example where this answer works and @zzzzBov's misses by 1 hour. Side by side test: `var timestamp = Date.parse("2011-03-26T20:59:59.999Z"); var d1 = new Date(timestamp); d1.setSeconds(d1.getSeconds() + 10); var d2 = new Date(timestamp + 10000); console.log(d1); console.log(d2);` using IE 11 and with system time set to Yekaterinburg. I'm not sure how likely it is, but it exists. – tsemer Jan 04 '18 at 16:41
11

Try this

a = new Date();
a.setSeconds(a.getSeconds() + 10);
lostyzd
  • 4,515
  • 3
  • 19
  • 33
5

I have a couple of new variants

  1. var t = new Date(Date.now() + 10000);
  2. var t = new Date(+new Date() + 10000);
1nstinct
  • 1,745
  • 1
  • 26
  • 30
4
timeObject.setSeconds(timeObject.getSeconds() + 10)
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

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:

trinaldi
  • 2,872
  • 2
  • 32
  • 37
coding_is_fun
  • 1,021
  • 10
  • 5
2
  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)
    
clemens
  • 16,716
  • 11
  • 50
  • 65
Javed IN
  • 302
  • 1
  • 4
  • 12
2

The .setSeconds revealed quite strange misbehavior for me under node.js, so I use:

dateAddSeconds(date, seconds){ 
    return new Date( Date.parse(date) + seconds*1000 );
}
T.Todua
  • 53,146
  • 19
  • 236
  • 237
1

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)

Ikram Ud Daula
  • 1,213
  • 14
  • 21
1

If you need to add 10 seconds to current time you can use:

const date = new Date();
date.setUTCSeconds(date.getUTCSeconds() + 10); // Change 10 to any number of seconds
AnasSafi
  • 5,353
  • 1
  • 35
  • 38
0

Few years ago i've wrote a 'generic' date function:

function addToDate({time_unit, operator, offset_value }) {
        const date = new Date();
  operator = operator == "after" ? "+" : "-";
  switch (time_unit) {
    case "seconds":
        date.setSeconds(eval(`${date.getSeconds()} ${operator} ${offset_value}`));
    break;

    case "hours":
        date.setHours(eval(`${date.getHours()} ${operator} ${offset_value}`));
      break;

    case "minutes":
        date.setMinutes(eval(`${date.getMinutes()} ${operator} ${offset_value}`));

      break;
    case "days":
        date.setDate(eval(`${date.getDate()} ${operator} ${offset_value}`));
      break;

    case "months":
        date.setMonth(eval(`${date.getMonth()} ${operator} ${offset_value}`));

      break;
    case "years":
        date.setFullYear(eval(`${date.getFullYear()} ${operator} ${offset_value}`));
      break;
    default:
      break;
  }

  return date;
}

const new_date = addToDate({time_unit:'seconds','operator':'after','offset_value':10});

console.log(new_date.toISOString());
Eran Peled
  • 767
  • 6
  • 6