javascript - 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!)
解决方案
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());
推荐阅读
- python - Pandas 使用 np.array().T 初始化数据帧
- websocket - Gravitee.io websocket 连接
- json - 如何在 FlatList React Native 中显示 JSON 数据
- rest - 什么是 goolge 驱动 API?
- angular - Angular FormGroup FormArray - 从下拉列表中仅提交数组中的一个对象
- ios - 如何将视图添加为 UITableViewCell 的子视图,但在所有其他视图之上
- c# - C# 使用自定义结构填充树视图
- python - 在python中使用魔杖计算图像的平均颜色基线
- jquery - 单击链接时弹出,有点像 css 中的 stackoverflow 收件箱
- php - Laravel 中的发布路线