Safari JS cannot parse YYYY-MM-DD date format?

后端 未结 4 2158
[愿得一人]
[愿得一人] 2020-11-28 10:38

In a project I am working on, I need to validate a date entered into an

With Safari 4/5 (on Mac OSX) the Javascript fails to

4条回答
  •  不知归路
    2020-11-28 10:46

    You can get an unambiguous date from input, but you still need to check it, so a user doesn't give you April 31.

    shortcut for document.getElementsByName

    function byName(s, n){ n= n || 0; return document.getElementsByName(s)[n]; }

    function getDateInput(){
        var day, y= parseInt(byName('inputyear').value),
        m= byName('monthselect').selectedIndex,
        d= parseInt(byName('inputdate').value);
    
        if(!y || y<1000 || y> 3000) throw 'Bad Year '+y;
        if((!d || d<1 || d> 32) throw 'Bad Date '+d;
        day= new Date(y,m,d);
        if(day.getDate()!= d) throw 'Bad Date '+d;
        value= day.format_mysql();
    }
    

    you can preset the fields to reflect the current date onload

    onload= function(){
        var now= new Date();
        byName('inputyear').value= now.getFullYear();
        byName('monthselect').selectedIndex= now.getMonth();
        byName('inputdate').value= now.getDate();
    }
    

提交回复
热议问题