简体   繁体   中英

How to compare input of date to hard coded date in if statement?

I am creating a web form and the user inputs a date and I want to compare it against a date to show the availability printed elsewhere and the "show date is the user input and the "2019-05-21" is the data I want to compare to.

if (document.getElementById("showDate").value === 2019-05-21 && document.getElementById("selection").value === "Les Miserables")
{
    document.getElementById("displayAva").innerHTML = "65 tickets left";
}

2019-05-21 isn't a date.

Just run this code:

 console.log(2019-05-21) 

The output is 1993 , you are doing math operations. Instead, you should use string or Date .

I don't know what is the value of document.getElementById("showDate").value , but if it's string you could simply do:

document.getElementById("showDate").value == "2019-05-21"

By that way, you would be comparing two strings. If showDate.value is exactly "2019-05-21" it will return true.

Using Date you might do:

Date.parse(document.getElementById("showDate").value) == Date.parse("2019-05-21")

Or if the other value is already Date :

document.getElementById("showDate").value.getTime() == Date.parse("2019-05-21")

Or:

document.getElementById("showDate").value.toUTCString() == new Date("2019-05-21").toTimeString()

They are just different ways to compare it, use what you find best for you.

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