Javascript减去日期

时间:2013-11-15 20:57:20

标签: sharepoint sharepoint-2010

我正在创建一个交通信号灯系统,可以动态地比较今天和截止日期,并相应地填充计算列。我能够对其进行编码,但用户更改了要求。而不是黄色红绿灯显示该项目是否到期今天,他们希望它显示该项目是否在接下来的5天内到期。

我想将它从“else if(fieldDate == today)”更改为今天前五天。我无法弄清楚在JavaScript中创建今天的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>

1 个答案:

答案 0 :(得分:0)

我错误地将你的fieldDate误认为是Date对象,当它们实际上只是长(毫秒)时。这就是你想要做的。

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

背后的逻辑是我后来的一条评论。

如果您只想在5天内进行一次检查:

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