如何使用Typescript检查Date数据类型变量是否过去?

时间:2014-07-27 12:27:38

标签: javascript typescript

我有这个功能:

   isAuthenticationExpired = (expirationDate: Date) => {
        var now = new Date();
        if (expirationDate - now > 0) {
            return false;
        } else {
            return true;
        }
    }

expirationDatenow都是Date

类型

Typescript给我一个错误说:

Error   3   The left-hand side of an arithmetic operation must be of type 
'any', 'number' or an enum type.    

Error   4   The right-hand side of an arithmetic operation must be of type 
'any', 'number' or an enum type.    

如何检查日期是否已过期,因为我的方式似乎无效?

2 个答案:

答案 0 :(得分:5)

使用now获取 Date expirationDate.valueOf()的整数值表示(自unix纪元以来 ms

var now = new Date().valueOf();
expirationDate = expirationDate.valueOf();

或者,使用Date.now()

答案 1 :(得分:2)

标准JS Date对象比较应该有效 - 请参阅here

module My 
{
    export class Ex 
    {
        public static compare(date: Date)
            : boolean
        {
            var now = new Date();       
            var hasExpired = date < now;
            return hasExpired;
        }
    }
}

var someDates =["2007-01-01", "2020-12-31"]; 

someDates.forEach( (expDate) =>
{
    var expirationDate = new Date(expDate);
    var hasExpired = My.Ex.compare(expirationDate);

    var elm = document.createElement('div');
    elm.innerText = "Expiration date " + expDate + " - has expired: " + hasExpired;    
    document.body.appendChild(elm);
});

更多信息: