Javascript日期时间比较返回false但仍然执行分支stmt

时间:2011-05-18 16:30:21

标签: javascript

我对这个Javascript行为感到困惑。检查此代码。

var NoOfMonthsElapsed = 6; //Should be >= 1 and <= 12
var MsgURL = "about:blank";
var PopupTitle = "ContactInfoUpdate";
var OptionString = "height=165,width=400,menubar=0,toolbar=0,location=1,status=0,resizable=0,status=0,HAlign=center,top=300";

var lastUpdatedDate = crmForm.all.dxb_lastcontactinfoupdatedon.DataValue; //Reads a field with date value = 01 Jan 2010
if (lastUpdatedDate)
{
  var month = lastUpdatedDate.getMonth();
  var year  = lastUpdatedDate.getYear();
  var date  = lastUpdatedDate.getDate();

  month = month + NoOfMonthsElapsed;
  year  = year  + parseInt(month / 11);
  month = (month % 11);

  var today = new Date();
  var showPopupAfterDate = new Date();

  showPopupAfterDate.setYear(year);
  showPopupAfterDate.setMonth(month);

  var alertMsg  = "LastUpdatedDate          = "+ lastUpdatedDate + "\n"
  var alertMsg += "Today                    = "+ today + "\n"
  var alertMsg += "PopupAfterDate           = "+ showPopupAfterDate + "\n"
  var alertMsg += "Today>showPopupAfterDate = "+ (today>showPopupAfterDate) + "\n"

  alert(alertMsg);

  if (today>showPopupAfterDate); 
  {
    window.open(MsgURL, PopupTitle, OptionString);
  }
}
else 
{
  window.open(MsgURL, PopupTitle, OptionString);
}




//
// It displays the following output
//
LastUpdatedDate          = Wed May 18 20:56:00 UTC+0400 2011
Today                    = Fri May 18 20:23:49 UTC+0400 2011
PopupAfterDate           = Fri Nov 18 20:23:49 UTC+0400 2011
Today>showPopupAfterDate = false

为什么今天显示为2011年5月18日星期五...虽然2011年5月18日是星期三 为什么PopupAfterDate显示为2011年11月18日星期五... 即使日期比较返回错误; window.open仍然被执行。

3 个答案:

答案 0 :(得分:2)

您的尾随分号会关闭if语句:

if (today>showPopupAfterDate);
// --------------------------^

答案 1 :(得分:2)

您的{}混乱,您错误的地方有;

if (lastUpdatedDate) {   
    ....
    if (today>showPopupAfterDate)    { // notice I removed ;
        window.open(MsgURL, PopupTitle, OptionString);   
    } 
} else  {
   window.open(MsgURL, PopupTitle, OptionString); 
}

答案 2 :(得分:1)

发现问题:

  if (today>showPopupAfterDate) //<-- remove the `;`
  {
    window.open(MsgURL, PopupTitle, OptionString);
  }

您的代码正在运行if,停止,然后执行下一个window.open

语句