2014-07-27 52 views
2

我有這樣的功能:如何使用Typescript檢查Date數據類型變量是否過去?

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

兩個expirationDatenow是Date類型的

打字稿給我一個錯誤說:

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

您可以直接使用' - '不減去日期。但你可以這樣做:'expirationDate.getTime()> now.getTime()' – techfoobar

回答

4

獲取整數值表示(在自Unix紀元毫秒)的日期nowexpirationDate使用.valueOf()

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

或者,使用Date.now()

1

標準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); 
}); 

更多信息:

相關問題