题
我已经完成了一个改变日期的函数,如果是一个周末,而不是给我第二天给我一天+ 1,例如我有一个输入的输入是最后一个星期天。
我有我的功能
<script type="text/javascript">
function getdate2() {
var items = new Array();
var itemCount = document.getElementsByClassName("datepicker hasDatepicker");
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() < 9 ? "0" : "")+ (itemDt.getDate()+2)+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();
}
if (itemDt.getDay() == 0) {
itemCount[i].value = (itemDt.getDate() < 9 ? "0" : "")+ (itemDt.getDate()+1)+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();
}
}
return items;
}
</script>
.
但不是给我的第一个10月,它给了我31-09-2012,这不存在。
我真的不知道如何处理。
解决方案
您需要在数组中每月存储最大天数。
var dayspermonth = new array(31,28,31,30,31,30,31,31,30,31,30,31);
.
最好在单独的功能中进行:
function int lastDay(d, m){
var result = d
var dayspermonth = new array(31,28,31,30,31,30,31,31,30,31,30,31);
if(d > dayspermonth[m]){
d=1;
}
return d;
}
.
然后你必须做(例如):
itemCount[i].value = (itemDt.getDate() < 9 ? "0" : "")+ lastDay((itemDt.getDate()+1), itemDt.getMonth())+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();
.
编辑: 如果发生这种情况,您需要将月份增加1。如果旧日期为31-12-yyyy ,则需要增加1到年份并将一个月设置为1
其他提示
2012/07/25 - 星期六。代码检查其周六 - 如果是星期天,请添加2天 - 添加1天 http://jsfiddle.net/s3q4p/
var mydate=new Date(2012,07,25)
if(mydate.getDay() == 6) //Saturday
mydate =new Date(mydate.getFullYear(),mydate.getMonth(),mydate.getDate()+2)
else if (mydate.getDay() == 0) //Sunday
mydate =new Date(mydate.getFullYear(),mydate.getMonth(),mydate.getDate()+1)
. 不隶属于 StackOverflow