我有一个带有id的年份列表,从日期到日期如下:
我遇到条件重叠日期的问题。我想将id 2的from_date编辑为2013-02-22和2013-03-01之间的日期,或者编辑期间1的to_date到2013-02-22和2013-03-01之间的日期,但它只允许1根据我的下面的代码。
以下是我的代码片段:
function validate(id){
//id is passed as a parameter to the function
from_date = document.getElementById('from_date_' + id);
to_date= document.getElementById('to_date_' + id);
var from = new Date();
var to = new Date();
// I am able to split the string, .split("-") and convert it in date format
previous_to_date = document.getElementById("to_" + id);//id is one less
next_from_date = document.getElementById("from_date_" + id);//id is one more
current_from_date //I store it before editing the from date
current_to_date //Similarly for current from date
//from_date and to_date are the edited dates by the user
if (from_date > to_date){ alert("This date is invalid"); return false; }
//now to check for overlapping dates
**//This is the condition I am having problems with**
if ((from_date < current_from_date && from_date < previous_to_date) || (to_date > current_to_date && to_date > next_from_date) && from_date > current_to_date){
alert("These dates overlap,Please select another date");
return false;
}
//successful so now we submit the form...
}
答案 0 :(得分:0)
简单来说,如果当前的日期之间存在差距 期间和前一期间的日期,我应该能够 编辑更改以将差距最小化至最多1。
var to_previous = "2013-02-22"
var from = "2013-03-01"
var to_previous_millis = Date.parse(to_previous);
var from_millis = Date.parse(from);
one_day = 1000*60*60*24;
while( (from_millis - to_previous_millis) >= one_day) {
current = new Date(from_millis);
console.log(current.toUTCString());
from_millis -= one_day
}
--output:--
Fri, 01 Mar 2013 00:00:00 GMT
Thu, 28 Feb 2013 00:00:00 GMT
Wed, 27 Feb 2013 00:00:00 GMT
Tue, 26 Feb 2013 00:00:00 GMT
Mon, 25 Feb 2013 00:00:00 GMT
Sun, 24 Feb 2013 00:00:00 GMT
Sat, 23 Feb 2013 00:00:00 GMT
var attempts = [
"2013-2-28",
"2013-2-23",
"2013-2-22"
];
var len = attempts.length;
for (var i=0; i < len; ++i) {
var attempt = attempts[i];
attempt_millis = Date.parse(attempt);
if (attempt_millis >= (to_previous_millis + one_day) ) {
console.log(attempt + " : valid change");
}
else {
console.log(attempt + " : invalid change");
}
}
--output:--
2013-2-28 : valid change
2013-2-23 : valid change
2013-2-22 : invalid change