我有这个功能:
isAuthenticationExpired = (expirationDate: Date) => {
var now = new Date();
if (expirationDate - now > 0) {
return false;
} else {
return true;
}
}
expirationDate
和now
都是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.
如何检查日期是否已过期,因为我的方式似乎无效?
答案 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);
});
更多信息: