开发者

Javascript date time comparison returns false but branch stmt still executed

开发者 https://www.devze.com 2023-03-06 15:54 出处:网络
I am confused with this Javascript behaviour. Check this code. var NoOfMonthsElapsed = 6; //Should be >= 1 and <= 12

I am confused with this Javascript behaviour. Check this code.

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 开发者_StackOverflow中文版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

Why today is shown as Fri May 18 2011... though May 18 2011 is Wed Why PopupAfterDate is shown as Fri Nov 18 2011... And Even though the dates comparission returns false; The window.open still get executed.


Your { and } are messy and you have a ; at the wrong place.

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


Your trailing semicolon closes the if statement:

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


Found the issue:

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

Your code is running the if, stopping, then doing the next statement which is the window.open

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号