我正在尝试以毫秒为单位将当前时间增加五分钟,而为什么加法和减法会得出这样的不同结果感到困惑:
const now = new Date();
const gimmeFive = now + 300000;
const takeFive = now - 300000;
分别给出:
"Sun May 31 2020 23:06:48 GMT+0100 (British Summer Time)300000"
1590962508207
为什么减法有效,但加法无效?如何增加时间?
为每个堆栈溢出提示添加了说明:虽然此处的Q与Add 10 seconds to a Date重叠,但在试图理解为什么加法和减法运算符表现出不同行为方面有所不同(如所解释的)感谢RobG!)
答案 0 :(得分:3)
为什么减法有效,但加法无效?如何增加时间?
如user120242在第一条评论中所述,addition operator (+)被重载,并根据所使用的值的类型进行算术加法或字符串加法(并置)(请参阅Runtime Semantics: ApplyStringOrNumericBinaryOperator)。
因此,在以下情况下:
new Date() + 300000;
日期是第一个converted to a primitive,它返回一个字符串。如果左操作数或右操作数均为st,则它们都将转换为字符串,然后将两个字符串连接起来。
在以下情况下:
new Date() - 300000;
subtraction operator (-)将值强制转换为数字,因此将Date转换为其时间值,并减去右边的值。
如果您想为日期增加300秒,则可以使用以下其中一项:
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());
答案 1 :(得分:2)
尝试使用此Date.now()+300000
和Date.now()-300000
P.S。将所有内容放到您的常量中
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()
方法返回自UTC 1970年1月1日00:00:00以来经过的毫秒数。相反,您可以使用new Date().getTime()
–它也会以毫秒为单位返回数字。
答案 2 :(得分:1)
new Date()
返回一个对象。您不应该在对象上直接增加或减少时间。
相反,您可以使用Date.now()
返回自1970年1月1日起经过的当前时间(以毫秒为单位)。
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)
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
话虽如此,如果您的项目可行,我建议您与momentjs合作。当处理日期时,它确实是一个救生器。
我希望这会有所帮助。干杯。
答案 3 :(得分:0)
如果要处理几分钟,最好的解决方案是使用Date的getMinutes
和setMinutes
方法。
var dt = new Date();
console.log(dt)
dt.setMinutes( dt.getMinutes() + 100 );
console.log(dt)
dt.setMinutes( dt.getMinutes() - 100 );
console.log(dt)
答案 4 :(得分:0)
new Date(now.getTime() + 5 * 60000)
作为新日期总是返回Object
new Date() - 1 // Return (new Date).getMilliseconds() similar to "1"-1 = 0
new Date() + 1 // Return string similar to "1"+1 = "11"