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")
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With