我思故我强

js日期函数实例

取当天日期:

<script language="JavaScript" type="text/JavaScript">
<!--
function jsFmtDate()
{
var today = new Date();
var year = today.getYear();
var month = today.getMonth()+1;
var date = today.getDate();
var returndate = year+"-" + (month>9?month:("0"+month)) +"-"+ (date>9?date:("0"+date));
return(returndate);
}
//-->
</script>

判断是否日期字符

<script language=javascript>
String.prototype.isDate = function()
{
   var r = this.match(/^(\d{1,2})(-|\/)(\d{1,2})\2(\d{1,4})$/);
   if(r==null)return false; var d = new Date(r[4], r[1]-1, r[3]);
   return(d.getFullYear()==r[4]&&(d.getMonth()+1)==r[1]&&d.getDate()==r[3]);
}
alert("01/31/2000".isDate());
alert("01/41/2000".isDate());
</script>


<script language=javascript>
String.prototype.isDate = function()
{
   var r = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
   if(r==null)return false; 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]);
}
alert("2002-01-31".isDate());
alert("2002-01-41".isDate());
</script>


将"-",改为"/"的正规表达式
var sdate = new Date(objdateFrom.value.replace(/-/g,"\/"));

日期比较:
<script>
var ar = '2004-10-18';
var n1 = ar.replace(/-/g, "/");
var n2 = new Date();
var  date1  =  Date.parse(n1); 
var  date2  =  Date.parse(n2); 
var d = Math.ceil((date2-date1)/(24*60*60*1000));
if(d>0)
  alert("日期已经过期!");
</script>


 

posted on 2007-08-27 20:41 李云泽 阅读(917) 评论(0)  编辑  收藏 所属分类: javascript


只有注册用户登录后才能发表评论。


网站导航: