Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare a "MM/DD/YYYY" date with the Date() function in Javascript?

Tags:

javascript

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

For example:

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")
}
like image 563
user793468 Avatar asked Oct 08 '22 11:10

user793468


1 Answers

Convert the String to a Date using new Date(dateString). Then normalize today's date to omit time information using today.setHours(0, 0, 0, 0). Then you can just compare the dates as you have 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");
}

Demo: http://jsfiddle.net/w2sJd/

like image 50
gilly3 Avatar answered Oct 13 '22 10:10

gilly3