Date对象的整数加法/减法问题

时间:2014-09-12 04:40:16

标签: javascript

我正在使用本机Date对象,我意识到减法有效(返回一个表示两个日期之间的总毫秒数的整数),但是只需通过字符串连接组合它们。类似地,向日期添加一个整数(例如,我希望获得3000毫秒后的时间)将返回一个字符串,同时将一个整数减去一个日期。

只是想知道这是否是预期的行为以及我是否遗漏了什么?

2 个答案:

答案 0 :(得分:1)

+ operator因字符串而重载,-则没有。 你需要使用

var newVal=parseInt(new Date().getTime()) + 1000

答案 1 :(得分:1)

您可以简单地将当前日期转换为毫秒,添加所需的增量,然后将其转换回日期时间格式,并且您有增加的日期:

var d = new Date();
alert("Current DateTime: " + d);
var milliseconds = d.getTime();  //this will convert current date  into milliseconds.. 

//Now youw want to progress the date by 3000ms.. simply add it to the current date time..
milliseconds += 3000;

d = new Date(milliseconds); //your new incremented date

alert("After 3000ms: " + d);

<强> See the DEMO here