首页 > 解决方案 > adding and substracting time in Javascript

问题描述

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!)

标签: javascriptdatetime

解决方案


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());


推荐阅读