Home > Web Front-end > JS Tutorial > How to convert date format in JS

How to convert date format in JS

怪我咯
Release: 2017-06-29 10:17:53
Original
2197 people have browsed it

这篇文章主要介绍了javascript实现日期格式转换,非常的简单实用,项目中经常可以用到,这里推荐给大家

代码如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>日期输入</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("日期输入错误");
            }
        }
    }
}
 
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="请输入日期" class="date">
</body>
</html>
Copy after login

把输入的YYYY.MM.DD、YYYY。MM。DD、YYYYMMDD转为YYYY-MM-DD

CheckDT这个function是在度娘里找的。

很简单实用的功能吧,小伙伴们可以直接拿去使用。

The above is the detailed content of How to convert date format in JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template