2017-01-26 143 views
-1

所需的輸出Null值:我有一個日期變量傳遞一個需要相比,今天的日期並返回天氣是前或後的今天。然後,我想返回「是」或「否」來指示它是否活動的天氣。比較日期使用JavaScript

<script> 
    function calculate(currentlyEffective) { 

     var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()); 
     var expDate = currentlyEffective.Expiration_Date; 
     expDate = new Date(expDate).toUTCString(); 
     var result = ""; 

     if (expDate < now_utc) { 
      result = "No" 
     } 
     else { 
      result = "Yes" 
     } 
     return result; 
    } 

</script> 

問題:

  1. 一些被傳遞不具有價值,因爲他們還沒有過期的日期。這將返回Thu, 01 Jan 1970 00:00:00 GMT期望的輸出將在此處爲"Yes",即使日期會比今天更短,因爲它沒有到期日期,因此它的"Yes"仍然有效。

  2. 某些事情在計算中沒有正確發生。我的返回值始終是"Yes"

問題:

  1. 我是不是正確的比較這些日期與我的if else功能?

  2. 即使在我有一個日期在expDate這是在今天之前,我仍然會得到「是」作爲我的返回值。我究竟做錯了什麼?

回答

0

你比較字符串和日期對象與<?你能指望什麼?你不需要時間字符串,你所需要的時間爲一個數字:

var now=new Date().getTime();//current time as number (ms since...) 
var old=new Date(timestring).getTime();//time as number with a timestring ("12:20 ...") 
if(now<old){ 
alert("future date!"); 
} 

全碼:

function calculate(currentlyEffective) { 

    var now = new Date().getTime(); 
    var expDate = currentlyEffective.Expiration_Date; 
    expDate = new Date(expDate).getTime(); 

    return expDate<now?"Yes":"No"; 
} 

由於RobG指出,這可以被shortified,如使用<兩個對象,改掉將它們轉換爲數字,實際上調用getTime:

var calculate=(currentlyEffective)=>new Date(currentlyEffective.Expiration_Date)<new Date()?"Yes":"No"; 
+0

這可能會縮減爲'new Date(currentlyEffective.Expiration_Date) RobG

+0

關於:*「您正在比較兩個字符串與<」*。 * now_utc *是一個Date對象,* expDate *是一個字符串。 – RobG

+0

@RobG:was not that shure toString()obj called。感謝澄清和關於縮短的小記。添加到我的答案... –