javascript implements date format conversion

  • 2020-05-05 10:57:44
  • OfStack


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Enter the date </title>
<script>
window.onload = function(){
    var aLaydate = document.getElementsByClassName("date");
    for(var i = 0;i < aLaydate.length;i ++)
    {
        aLaydate[i].onchange = function(){
            var dateValue = this.value;
            dateValue = dateValue.replace(/\ . /g,"-");
            dateValue = dateValue.replace(/\./g,"-");
            if(dateValue.length == 8){
                var temp = dateValue.substring(0,4) + "-" + dateValue.substring(4,6) + "-" + dateValue.substring(6,8);
                dateValue = temp;
                console.log(dateValue);
            }
            if(CheckDT(dateValue)){
                this.value = dateValue;
            }
            else
            {
                alert(" Date error ");
            }
        }
    }
}
 
function CheckDT(str)   
{   
    var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);   
    if(r==null)
    {
        return false;   
    }
    else
    {
        var d= new Date(r[1], r[3]-1, r[4]);   
        return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
    }  
}
</script>
</head>
<body>
<input placeholder=" Please enter the date " class="date">
</body>
</html>

Enter YYYY.MM.DD, YYYY. MM. DD, YYYYMMDD to YYYY-MM-DD

CheckDT this function is found in baidu.

Very simple and practical functions, friends can be used directly.


Related articles: