js控制日期格式
第一种:
[html]<script>
function td(d){
var r=1,p='';
if(!/[^\d\-]/ig.test(d))p=d.split("-");else r=0;
if(p.length==3){if(p[1]<13&p[1]>0&p[2]>0){if(new Date(p[0],p[1],0).getDate()<p[2])r=0}else r=0}else r=0;
(r==1)?alert('正确'):alert('错误');}
</script>
<input value="2003-12-31" id="a"/><button onclick="td(a.value)">test[/html]
第二种:
function isDateString(sDate)
{
var iaMonthDays = [31,28,31,30,31,30,31,31,30,31,30,31]
var iaDate = new Array(3)
var year, month, day
if (arguments.length != 1) return false
iaDate = sDate.toString().split("-")
if (iaDate.length != 3) return false
if (iaDate[1].length > 2 || iaDate[2].length > 2) return false
year = parseFloat(iaDate[0])
month = parseFloat(iaDate[1])
day=parseFloat(iaDate[2])
if (year < 1900 || year > 2100) return false
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) iaMonthDays[1]=29;
if (month < 1 || month > 12) return false
if (day < 1 || day > iaMonthDays[month - 1]) return false
return true
}
第三种:
<input title="日期格式: 2003-09-22" onblur="if(strDateTime(value))alert('你的日期不对')">
<script language=javascript>
function strDateTime(str)
{
if(str=="") return false;
var r = str.match(/^(\d{4})(-)(\d{2})\2(\d{2})$/);
if(r==null)return true;
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>
第四种:
//判断客户端输入的年、月、日是否合法,方法2
function CheckIsDate(value)//格式为yyyy-mm-dd
{
var strValue = new String();
var year = new String();
var month = new String();
var day = new String();
strValue = value;
if (strValue.length!=10)
{
return false;
}
else
if (strValue.charAt(4)!='-'||strValue.charAt(7)!='-')
{
return false;
}
else
{
year = strValue.substr(0,4);
month = strValue.substr(5,2);
month = month-1;
day = strValue.substr(8,2);
var testDate = new Date(year,month,day)
//alert(testDate);
return (year == testDate.getFullYear()) && (month ==testDate.getMonth())&&(day == testDate.getDate());
}
return true;
}
alert(CheckIsDate("2002-04-31"));
</script>