简体   繁体   中英

advice with try catch javascript

I am trying to verify a date input with a try catch in java script, but the following code doesn't work as I expect it. I expect that the error when the entered date is not date, the catch should execute but here is what I get. see no new date and nothing displayed of what i expect.

console.log("min date :")
    try{
         minDate = new Date(elminDate.value)
    }
    catch(e){
        console.log("error::")
        console.log(err.name)
        console.log("changed min")
         minDate = new Date()
    }
    console.log(minDate)

    console.log("max date :" )
    try{
         maxDate = new Date(elmaxDate.value)
    }
    catch(err){
        console.log("error::")
        console.log(err.name)
        console.log("changed max")
        maxDate = new Date()
    }
    console.log(maxDate)

response :

[Log] min date : (home.html, line 93)
[Log] Tue Aug 01 2017 02:00:00 GMT+0200 (CEST) (home.html, line 103)
[Log] max date : (home.html, line 105)
[Log] Invalid Date (home.html, line 115)

The Date constructor doesn't throw exceptions on invalid dates, but rather produces a NaN value in the Date object. You can test for that:

console.log("date :");
date = new Date(elDate.value);
if (isNaN(date)) {
    console.log("error: Invalid Date");
    console.log("changed date to now");
    date = new Date();
}
console.log(date)

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