How to compare "MM / DD / YYYY" date with Date () function in Javascript?

How to compare the input date of the "MM / DD / YYYY" format with a function Date()in Javascript?

For instance:

if (InputDate < TodaysDate){
  alert("You entered past date")
}
else if (InputDate > TodaysDate){
  alert("You entered future date")
}
else if (InputDate = TodaysDate){
  alert("You entered present date")
}
else{
  alert("please enter a date")
}
+5
source share
5 answers

Thanks everyone! I did not find any of the above to work, but got it to work at last. Had a little hack;)

I did this by separating Date using getMonth, getDate and getYear, and parsed it and then compared it. It works the way I want:

Date.parse(document.getElementById("DateId").value) < Date.parse(dateToday.getMonth() + "/" + dateToday.getDate() + "/" + dateToday.getYear())
+2
source

Convert string to date with new Date(dateString). Then normalize the date today to omit the time information with today.setHours(0, 0, 0, 0). Then you can simply compare the dates above:

var date = new Date(dateInput);
if (isNaN(date)) {
    alert("please enter a date");
}
else {
    var today = new Date();
    today.setHours(0, 0, 0, 0);
    date.setHours(0, 0, 0, 0);
    var dateTense = "present";
    if (date < today) {
        dateTense = "past";
    }
    else if (date > today) {
        dateTense = "future";
    }
    alert("You entered a " + dateTense + " date");
}

: http://jsfiddle.net/w2sJd/

+3

Date.

You need one Date object with the entered date (using either the constructor, or methods setMonth, etc.), and one with the current date (without arguments to the constructor). Then you can use getTimeto get UNIX timestamps on both objects and compare them.

+1
source

Take a look at http://www.datejs.com/ . This will help you with the usual date processing.

0
source
function compareDate(inputDateString) {
  var inputDate, now;
  inputDate = new Date(inputDateString);
  now = new Date();
  if (inputDate < now) {
    console.log("You entered past date");
  }
  else if (inputDate > now) {
    console.log("You entered future date");
  }
  else if (inputDate === now) {
    console.log("You entered present date");
  }
  else {
    console.log("please enter a date");
  }
}
-3
source

All Articles