在Javascript中添加和减去时间 [英] adding and substracting time in Javascript

查看:83
本文介绍了在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;

分别给出:

"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?

为每个堆栈溢出提示添加澄清:而这里的问与向日期添加10秒重叠,不同之处在于了解为什么加法和减法运算符显示不同的行为(如RobG所解释的,对此非常感谢!)

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?

正如user120242在第一条评论中所述,加法运算符(+)重载,并且根据所使用的值的类型进行算术加法或字符串加法(连接)(请参见运行时语义:ApplyStringOrNumericBinaryOperator )。

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

因此,在以下情况下:

new Date() + 300000;

日期是第一个转换为原语,该原语返回一个字符串。如果左操作数或右操作数均为st,则它们都将转换为字符串,然后将两个字符串连接起来。

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.

在以下情况下:

new Date() - 300000;

减法运算符(-)将值强制转换为数字,因此将Date转换为其时间值,并减去右手值。

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

如果要为日期添加300秒,则可以使用以下选项之一:

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

这篇关于在Javascript中添加和减去时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆