更改日期的功能不起作用

时间:2012-08-29 06:30:58

标签: javascript function date weekend

在很多帮助下,我已经完成了一个函数,如果日期是周末,则检查onload,如果它是星期天,它必须增加一天。如果是星期六这一天有2加入它,因为不幸的是在法国没有人想在周末工作。

以下是我正在使用的代码:

<script type="text/javascript">
    function getdate() {
        var items = new Array();
        var itemCount = document.getElementsByClassName("date");

        for (var i = 0; i < itemCount.length; i++) {
            items[i] = document.getElementById("date" + (i + 1)).value;
        }



        for (var i = 0; i < itemCount.length; i++) {
            items[i] = document.getElementById("date" + (i + 1)).value;
            var itemDtParts = items[i].split("-");
            var itemDt = new Date(itemDtParts[2], itemDtParts[1] - 1, itemDtParts[0]);
            if (itemDt.getDay() == 6) {

                itemCount[i].value =  itemDt.getDate()+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();


            }
            if (itemDt.getDay() == 0) {

               itemCount[i].value = itemDt.getDate()+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();

            }

        }
       return items;
  }
</script>

一切正常,可以检查日期是否是周末,但是当我问日期+1时它不会改变。

我想改变星期六和星期日到星期一。

感谢您的帮助

SP。

1 个答案:

答案 0 :(得分:1)

你在哪里:

> var itemDt = new Date(itemDtParts[2], itemDtParts[1] - 1, itemDtParts[0]);
然后,您可以执行以下操作:

// Increment date if Saturday or Sunday
var inc = itemDt.getDay() == 0? 1 : itemDt.getDay() == 6? 2 : 0;

// Only update DOM if necessary
if (inc) {
  itemDt.setDate(itemDt.getDate() + inc);
  // Update DOM
} 

请注意,如果日期设置在月末之外(或在开始之前),则日期对象会进行调整,因此将日期设置为1月32日为2月1日。