简体   繁体   中英

Compare variable date with Date(dateString) in if/else statement

Sorry for the n00b question, but my js/jq is terrible. I spent the better part of my afternoon on this, but I still can't figure out the last little bit.

I need to input a date, calculate the date 180 days from the inputted date, and compare that with a dateString (labelled as 'deadline' in the code below). Everything works okay, except for the if/else statement at the end. I feel like it is a simple fix, but I just can't see it. Presently, it just outputs the result of the else statement.

HTML

<h2>click Go! to add 180 days:</h2>
<p>Add 180 to:
<input id="indexDate" type="text" />
<input type="button" onclick="getdate()" value="Go!" />

<p>Result Date:
<span id="date_180"></span>
<span id="answer"></span></p>

JS/JQ

$(document).ready(function () {
    $('#indexDate').datepicker({changeYear: true}).datepicker('setDate', '01/01/2004');
});

function getdate() {

  var tt = document.getElementById('indexDate').value;
  var date = new Date(tt);
  var newdate = new Date(date);
  var deadline = new Date(11/03/2014);

  newdate.setDate(newdate.getDate() + 180);

  var dd = newdate.getDate();
  var mm = newdate.getMonth() + 1;
  var y = newdate.getFullYear();

  var formattedDate = mm + '/' + dd + '/' + y;
  document.getElementById('date_180').innerHTML = formattedDate;

  if (formattedDate<deadline) {
    document.getElementById("answer").innerHTML = "Yay!";
  } else {
    document.getElementById("answer").innerHTML = "Boo!";
  }       
}    

Try this in your if condition

 if(new Date(formattedDate) < deadline){
     document.getElementById("answer").innerHTML = "Yay!";
  } else {
    document.getElementById("answer").innerHTML = "Boo!";
  }    

If not working try to format date likes

var formattedDate = new Date(Year,Month,Day);//Date object ref

I think ist a Problem with the formats of the Dates.

Add

console.log(deadline);
console.log(formattedDate);

before the if Block and have a look in the console. What does it say?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM