在 JS 中添加/减去时间 [英] adding / subtracting time in JS

查看:26
本文介绍了在 JS 中添加/减去时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在玩 JS,发现了一些有趣的东西.这就是我在 chrome 控制台中写的内容:

Lately I was playing with JS and I found something interesting. That is what I wrote into chrome console:

today = new Date()
-> Mon Apr 29 2013 13:06:01 GMT+0200 (CEST)
DAY = 1000 * 3600 * 24
-> 86400000
today - 2 * DAY
-> 1367060761452
today + 2 * DAY
-> "Mon Apr 29 2013 13:06:01 GMT+0200 (CEST)172800000"

而且我想知道为什么我会根据操作的类型得到不同类型的答案 - 加法/减法.当我做这样的事情时:

And I am wondering why am I getting different types of answer depending on the type of operation - adding / subtracting. When I do something like that:

today - (-2) * DAY

一切正常.有什么意识形态,还是bug?

everything is fine. Is there any ideology, or is it a bug?

推荐答案

这在规范中有点难找,因为它与 Date 的其余部分无关.

This is a bit tricky to find in the spec, because it's not with the rest of the Date stuff.

如果您查看 第 11.6.1 节,加法运算符",您会发现以下注释:

If you take a look at section 11.6.1, "The Addition operator," you'll find the following note:

注意 1 在第 5 步和第 6 步中对 ToPrimitive 的调用中没有提供任何提示.除 Date 对象之外的所有原生 ECMAScript 对象都处理没有提示的情况,就像给出了提示 Number 一样;日期对象处理没有提示的情况,就像给出了提示字符串一样.宿主对象可能会以其他方式处理没有提示的情况.

NOTE 1 No hint is provided in the calls to ToPrimitive in steps 5 and 6. All native ECMAScript objects except Date objects handle the absence of a hint as if the hint Number were given; Date objects handle the absence of a hint as if the hint String were given. Host objects may handle the absence of a hint in some other manner.

在上下文中,这意味着对 Date 对象使用加法运算符 (+) 将使用字符串值而不是数字值.从这个意义上说,Date 对象是特殊的,不同于任何其他类型的对象.

In context, that means using the addition operator (+) with a Date object will use the string value rather than the numeric value. In this sense, Date objects are special and unlike any other kind of objects.

请注意,减法运算符没有这样的例外,因为它是明确的 —它只适用于数字减法;它不对字符串进行操作.

Note that there is no such exception for the subtraction operator, as it is unambiguous — it only works for numeric subtraction; it doesn't operate on strings.

另请注意,这适用于加法运算符,即两边都有操作数的 +.一元加号"运算符不是这样工作的,所以 +myDateObj 在左侧没有任何内容将导致数值.

Also note that this applies to the addition operator, a + with operands on both sides. The unary "plus" operator does not work like this, so +myDateObj with nothing on the left hand side will result in the numeric value.

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

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