0

I'm trying to add five minutes to the current time using milliseconds and am baffled why adding and subtracting give such different results:

const now = new Date();
const gimmeFive = now + 300000;
const takeFive = now - 300000;

Respectively give:

"Sun May 31 2020 23:06:48 GMT+0100 (British Summer Time)300000"

1590962508207

Why does subtraction work, but not addition? How can I add time?


Added clarification per stack overflow prompt: while the Q here overlapped with Add 10 seconds to a Date, it differed in seeking to understand why the add and subtract operators show different behaviours (as explained by RobG, for which, much thanks!)

Mina
  • 150
  • 2
  • 12
  • 1
    coerce it to a number first or use .getTime() or Date.now. `+` with a Date will try to coerce to a string first. `-` is not an operator for strings, so it will try to coerce to number. It's part of the conversion rules. – user120242 May 31 '20 at 22:38
  • Does this answer your question? [Add 10 seconds to a Date](https://stackoverflow.com/questions/7687884/add-10-seconds-to-a-date) – user120242 May 31 '20 at 22:44
  • Does this answer your question? [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) – radulle May 31 '20 at 22:47
  • @Mina as to "why", it's because that's how the specs of the language are designed. You can follow the conversion path: https://www.ecma-international.org/ecma-262/6.0/#sec-addition-operator-plus basically ToPrimitive -> ToString is attempted first. And for subtraction: https://www.ecma-international.org/ecma-262/6.0/#sec-subtraction-operator-minus – user120242 May 31 '20 at 22:51

5 Answers5

3

Why does subtraction work, but not addition? How can I add time?

As user120242 says in the first comment, the addition operator (+) is overloaded and does either arithmetic addition or string addition (concatenation) depending on the types of values used (see Runtime Semantics: ApplyStringOrNumericBinaryOperator).

So in the case of:

new Date() + 300000;

the Date is first converted to a primitive, which returns a string. If either the left or right operands are stings, they're both converted to string and then the two strings are concatenated.

In the case of:

new Date() - 300000;

the subtraction operator (-) coerces values to number, so the Date is converted to its time value and the right hand value is subtracted.

If you want to add 300 seconds to a Date, you can use one of the following:

let d = new Date();
let ms = 300000;

// Add 3 seconds to the time value, creates a new Date
let e = new Date(d.getTime() + ms)
console.log(e.toString());

// As above but use unary operator + to coerce Date to number
let f = new Date(+d + ms)
console.log(f.toString());

// Use get/setMilliseconds, modifies the Date
d.setMilliseconds(d.getMilliseconds() + ms)
console.log(d.toString());

// Use Date.now
let g = new Date(Date.now() + ms);
console.log(g.toString());
RobG
  • 142,382
  • 31
  • 172
  • 209
2

Try this Date.now()+300000 and Date.now()-300000

P.S. put everything on your constants of course

typeof (new Date)   // returns "object"
typeof (Date.now()) // returns "number"

/* --------------------------------- //
SO, of course, you cannot add or subtract numbers from, 
and to objects. Follow the rules, make calculations with 
numbers and everything will be OK. 
*/


// your code might look like this
const now = Date.now();
const gimmeFive = now + 300000;
const takeFive = now - 300000;

Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC. Instead you can use new Date().getTime() – it will also return you a number in milliseconds.

Robbie KN
  • 317
  • 1
  • 8
1

new Date() returns an object. You should not be adding or subtracting time directly on the object.

Instead, you can use Date.now() which returns the current time in milliseconds elapsed since Jan 1 1970.

const now = Date.now();
const gimmeFive = now + 300000;
const takeFive = now - 300000;

console.log(new Date(gimmeFive)); // Sun May 31 2020 18:42:20 GMT-0400 (Eastern Daylight Time)
console.log(new Date(takeFive)); // Sun May 31 2020 18:32:20 GMT-0400 (Eastern Daylight Time)

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

That being said, if it is possible in your project, I suggest working with momentjs. It is truly a life saver when it comes to manipulating dates.

I hope this helps. Cheers.

Antoine Cloutier
  • 1,330
  • 11
  • 23
0

If you are working with minutes best solution is to use Date's getMinutes and setMinutes methods.

var dt = new Date();
console.log(dt)

dt.setMinutes( dt.getMinutes() + 100 );
console.log(dt)

dt.setMinutes( dt.getMinutes() - 100 );
console.log(dt)
radulle
  • 1,437
  • 13
  • 19
0
new Date(now.getTime() + 5 * 60000)

as new Date always return Object,

new Date() - 1 // Return (new Date).getMilliseconds() similar to "1"-1 = 0
new Date() + 1 // Return string similar to "1"+1 = "11"
Gaurav Mogha
  • 370
  • 3
  • 9