添加未来的时间并进行比较

时间:2014-02-11 00:44:31

标签: javascript jquery date

如果已经提出这个问题,我很抱歉,但我找不到我的问题。

我已经看到了这一点,但我不确定它返回的数字代表什么:Date() * 1 * 10 * 1000

我想设置一个未来时刻,然后将其与Date()的当前实例进行比较,看看哪个更大。可能是未来几秒钟,几分钟,几小时或几天。

以下是我的代码:

var futureMoment = new Date() * 1 *10 * 1000;
console.log('futureMoment = ' + futureMoment);

var currentMoment = new Date();
console.log('currentMoment = ' + currentMoment);

if ( currentMoment < futureMoment) {
    console.log('currentMoment is less than futureMoment.  item IS NOT expired yet');
}
else {
    console.log('currentMoment is MORE than futureMoment.  item IS expired');
}

4 个答案:

答案 0 :(得分:3)

Javascript日期基于自Epoch(1970年1月1日00:00:00 UTC)以来的毫秒数。

因此,要计算未来日期,请添加毫秒。

var d = new Date();
var msecSinceEpoch = d.getTime();  // date now
var day = 24 * 60 * 60 * 1000; // 24hr * 60min * 60sec * 1000msec
var futureDate = new Date(msecSinceEpoc + day);

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

答案 1 :(得分:1)

var futureMoment = new Date() * 1 *10 * 1000;

变为

var now = new Date();
var futureMoment = new Date(now.getTime() + 1 *10 * 1000);

我认为你的意思是增加时间。不要倍增它。

答案 2 :(得分:0)

如果你处理时间,有很多工具可供选择 试试moment library

答案 3 :(得分:0)

使用以下代码将所选日期时间与当前日期时间进行比较

var dt = "Thu Feb 04 2016 13:20:02 GMT+0530 (India Standard Time)"; //this date format will receive from input type "date"..
function compareIsPastDate(dt) {    
    var currDtObj = new Date();
    var currentTime = currDtObj.getTime();

    var enterDtObj = new Date(dt);
    var enteredTime = enterDtObj.getTime();

    return (currentTime > enteredTime);   
}