javascript實現(xiàn)日期格式轉(zhuǎn)換
更新時間:2014年12月16日 10:40:30 投稿:hebedich
這篇文章主要介紹了javascript實現(xiàn)日期格式轉(zhuǎn)換,非常的簡單實用,項目中經(jīng)??梢杂玫剑@里推薦給大家
復(fù)制代碼 代碼如下:
<!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>
把輸入的YYYY.MM.DD、YYYY。MM。DD、YYYYMMDD轉(zhuǎn)為YYYY-MM-DD
CheckDT這個function是在度娘里找的。
很簡單實用的功能吧,小伙伴們可以直接拿去使用。
相關(guān)文章
jQuery設(shè)置和獲取select、checkbox、radio的選中值方法
select、checkbox、radio是很常用的表單控件,這篇文章主要介紹了jQuery設(shè)置和獲取select、checkbox、radio的選中值方法,有興趣的可以了解一下。2017-01-01《JavaScript高級程序設(shè)計》閱讀筆記(三) ECMAScript中的引用類型
ECMAScript中的引用類型,主要包括Object類、Boolean類、Number類、String類、instanceof運(yùn)算符2012-02-02JS從一組數(shù)據(jù)中找到指定的單條數(shù)據(jù)的方法
這篇文章給大家介紹基于js如何從一組數(shù)據(jù)中找到指定的單條數(shù)據(jù),非常實用,實現(xiàn)方案也很簡單,需要的朋友可以參考下2016-06-06js與jQuery實現(xiàn)的用戶注冊協(xié)議倒計時功能實例【三種方法】
這篇文章主要介紹了js與jQuery實現(xiàn)的用戶注冊協(xié)議倒計時功能,結(jié)合實例形式分析了三種倒計時功能的相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2017-11-11