Javascript 用js编写复杂的if语句

Javascript 用js编写复杂的if语句,javascript,html,if-statement,Javascript,Html,If Statement,我有一份id为的年份列表,从日期到日期如下: 从\u日期到\u日期的id 1 2013-02-12 2013-02-22 2 2013-03-01 2013-03-28 3 2013-03-29 2013-04-15 等等 我有重叠日期的问题,如果条件。我想从id为2的日期编辑到2013-02-22和2013-03-01之间的日期,或从期间1的日期编辑到2013-02-22和2013-03-01之间的日期,但根据下面的代码,它只允许1

我有一份id为的年份列表,从日期到日期如下:

从\u日期到\u日期的id 1 2013-02-12 2013-02-22 2 2013-03-01 2013-03-28 3 2013-03-29 2013-04-15 等等 我有重叠日期的问题,如果条件。我想从id为2的日期编辑到2013-02-22和2013-03-01之间的日期,或从期间1的日期编辑到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...
}
更简单地说,如果当前日期的起始日期之间存在差距 期间和上一期间的截止日期,我应该能够 编辑更改以将间隙最小化为最多1


问题在哪里?我们可以看看你现有的代码吗?也许我们可以在此基础上再接再厉。如果不是一个循环,只是为了学习。是我的错。我的意思是,如果你能建议一些关于我的代码,请。谢谢,收起它。然后研究我的代码。在您的代码中,from_date是一个字符串,您正在将它与其他字符串进行比较。字符串与日期有什么关系?我将所有字符串转换为日期。我使用.split分割字符串-然后字符串[0]是年,字符串[1]-1是月,字符串[2]是日期。然后我使用date.set[0]、[1]、[2]将其转换为日期。我已经检查了这个,它正确地转换了日期,所以在我的示例中,如果我比较整数
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