JavaScript to validate date

前端 未结 2 1704
抹茶落季
抹茶落季 2021-01-24 01:19

Below is the function to validate date. The should be between Today - 15 and Today. Can some one refactor this code.

phpdatetoday is a

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-24 02:01

    function validate(phpdatetoday, withinDays) {
        var inputDateInMillis = Date.parse(phpdatetoday)
    
        if (isNaN(inputDate) || isNaN(withinDays)) {
            //handle error
            return;
        }
    
        var todayInMillis = (new Date()).setHours(0,0,0,0);
        return todayInMillis - inputDateInMillis < (withinDays * 86400000 /*1000ms*60s*60m*24h*/);
    }
    

    Date.setHours() will set the hours/minutes/seconds to zero and return milliseconds since 1 Jan 1970 UTC.

    Date.parse() will return the parsed date otherwise if it cannot do it then it will return NaN. You can use isNan() to determine whether a variable's value is a number or not. If 'inputDate' is NaN then you can alert the user that the input date was invalid.

提交回复
热议问题