2013-11-15 219 views
0

我正在創建一個交通燈系統,它可以動態比較今天的截止日期和相應的填充計算列。我能夠對其進行編碼,但用戶更改了需求。他們希望它顯示該物品是否在未來5天內到期,而不是黃色紅綠燈顯示物品是否到期。JavaScript減去日期

我希望將它從「else if(fieldDate == today)」改爲今天的前五天。我無法弄清楚在JavaScript中創建today - 5對象的正確方法。幫幫我!

<script type="text/javascript"> 
//<!-- This script searches for calculated fields that are "marked" vith "Due:" and   --> 
//<!-- Create a calculated field in the list with the following formula:     --> 
//<!-- =IF(DueDate="","N/A","Due: "&MONTH(DueDate)&"/"&DAY(DueDate)&"/"&YEAR(DueDate))  --> 
//<!-- The data type returned from this formula is: Date and Time       --> 
// call script 

findDatefields(); 
function findDatefields() { 
    var d = new Date(); 
    var today = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); 
    var arr = document.getElementsByTagName('td'); 
    for (var i = 0; i < arr.length; i++) { 

     // Check if it is "our field" 

     if ((arr[i].className == "ms-vb2") && (arr[i].innerHTML.indexOf("Due:") == 0)) { 
      var sepDate = arr[i].innerHTML.substring(5).split("/", 3); 
      var m = sepDate[0]; 
      var d = sepDate[1]; 
      var y = sepDate[2]; 

      // build the datestring 
      var fieldDate = new Date(y, m - 1, d, 00, 00, 00).getTime(); 
      if (fieldDate > today) { 
       arr[i].innerHTML = "<IMG src='_layouts/images/KPIDefault-0.gif' Title='On track' />"; 
      } 

      else if (fieldDate == today) { 
       arr[i].innerHTML = "<IMG src='_layouts/images/KPIDefault-1.gif' Title='Due today' />"; 

      } 

      else { 
       arr[i].innerHTML = "<IMG src='_layouts/images/KPIDefault-2.gif' Title='Overdue' />"; 
      } 
     } 
    } 
} 

// For it to work in collapsed views 

function ExpGroupRenderData(htmlToRender, groupName, isLoaded) { 
    var tbody = document.getElementById("tbod" + groupName + "_"); 
    var wrapDiv = document.createElement("DIV"); 
    wrapDiv.innerHTML = "<TABLE><TBODY id=\"tbod" + groupName + "_\" isLoaded=\"" + isLoaded + "\">" + htmlToRender + "</TBODY></TABLE>"; 
    tbody.parentNode.replaceChild(wrapDiv.firstChild.firstChild, tbody); 
    findDatefields(); 
} 
</script> 

回答

0

我誤以爲你的fieldDate和今天是Date對象,當它們實際上只是longs(毫秒)。這是你想要做的。

else if ((fieldDate - today) <= 432000000) 

背後的邏輯是在我後面的評論之一。

如果你想對剛剛5天,單次檢查:

else if (fieldDate == (today + 432000000)); 
+0

我想這一點,這是行不通的。我想在今天之前設置一個5天的變量,然後將其與該變量進行比較。 fieldDate必須大於或等於Today - 5(即最近5天內) – thunderxlt

+0

已更新爲在5天內執行檢查。 –

+0

您也可以用您在其他地方設置的變量替換5。 –