将时间段添加/减去当前时间(Javascript)

时间:2012-05-17 10:07:12

标签: javascript date

我有点困惑!我有以下一点JS

//Set datetimes for the centre of the Timeline and the highlighting period
var myCurrentDateTime = new Date();
var MS_PER_MINUTE = 60000;
var MinsToDeductForCentre = 1440
var MinsEitherSideOfNow = 720
var myTLcenterdate = new Date(myCurrentDateTime - (MinsToDeductForCentre * MS_PER_MINUTE));
var tldate = myTLcenterdate.toString()
var hlStartDate = new Date(myCurrentDateTime - (MinsEitherSideOfNow * MS_PER_MINUTE));
var hlEndDate = new Date(myCurrentDateTime + (MinsEitherSideOfNow * MS_PER_MINUTE));    

myTLcentredate在当前时间之前24小时给我一个日期

hlStartDate在当前时间之前12小时给我一个日期

但是hlEndDate给出了Notanumber错误......

它基本上将myCurrentDateTime和MinsEitherSideOfNow * MS_PER_MINUTE(43200000)的值视为字符串并加入它们,例如“Thu May 17 10:44:17 UTC + 0100 201243200000”

为什么?

3 个答案:

答案 0 :(得分:4)

如果您想在日期中添加或减去分钟,这就足够了:

var dSubtract = new Date, 
    dAdd = new Date;
// let dSubtract be Thu May 17 2012 12:11:54 GMT+0200
// and dAdd         Thu May 17 2012 12:11:54 GMT+0200
dSubtract.setMinutes(dSubtract.getMinutes()-1440); 
//=> dSubtract is now: Wed May 16 2012 12:00:54 GMT+0200
dAdd.setMinutes(dAdd.getMinutes()+720);
//=> dAdd is now: Fri May 18 2012 00:00:54 GMT+0200

(在我的时区中的例子)

答案 1 :(得分:0)

对两个变量使用函数parseInt,如下所示:

parseInt(var1) * parseInt(var2)

答案 2 :(得分:0)

试试这个

function SubtractTime(objStartdatetime, objEnddatetime) {
//var T1 = new Date("2012/02/14 8:10:00");

d = new Date();
     T1 = new Date(objStartdatetime);
     T2 = new Date(objEnddatetime);        
      misec = T2.getTime() - T1.getTime();

}

function AddTime(objStartdatetime,objEnddatetime){     // var T1 = new Date(“2012/02/14 8:10:00”);

d = new Date();
     T1 = new Date(objStartdatetime);
     T2 = new Date(objEnddatetime);        
      misec = T2.getTime() + T1.getTime();

}