JS 中几个常用日期函数

出自:http://www.aspxhome.com/javascript/skills/20081/292130.htm

日期比较函数用法
<script language="javascript">
function DateDiff(interval,date1,date2){
var long = date2.getTime() - date1.getTime(); //相差毫秒
switch(interval.toLowerCase()){
case "y": return parseInt(date2.getFullYear() - date1.getFullYear());
case "m": return parseInt((date2.getFullYear() - date1.getFullYear())*12 + (date2.getMonth()-date1.getMonth()));
case "d": return parseInt(long/1000/60/60/24);
case "w": return parseInt(long/1000/60/60/24/7);
case "h": return parseInt(long/1000/60/60);
case "n": return parseInt(long/1000/60);
case "s": return parseInt(long/1000);
case "l": return parseInt(long);
}
}
alert(DateDiff("d",new Date(2008,03,01),new Date(2008,03,20)));
</script>

日期加法
<script language="javascript">
function DateAdd(interval,number,date){
switch(interval.toLowerCase()){
case "y": return new Date(date.setFullYear(date.getFullYear()+number));
case "m": return new Date(date.setMonth(date.getMonth()+number));
case "d": return new Date(date.setDate(date.getDate()+number));
case "w": return new Date(date.setDate(date.getDate()+7*number));
case "h": return new Date(date.setHours(date.getHours()+number));
case "n": return new Date(date.setMinutes(date.getMinutes()+number));
case "s": return new Date(date.setSeconds(date.getSeconds()+number));
case "l": return new Date(date.setMilliseconds(date.getMilliseconds()+number));
}
}
alert(DateAdd("s",1,new Date()));
</script>

判断是否是日期
<script language="javascript">
function IsDate(dateval){
var arr = new Array();
if(dateval.indexOf("-") != -1){
arr = dateval.toString().split("-");
}else if(dateval.indexOf("/") != -1){
arr = dateval.toString().split("/");
}else{
return false;
}

//yyyy-mm-dd || yyyy/mm/dd
if(arr[0].length==4){
var date = new Date(arr[0],arr[1]-1,arr[2]);
if(date.getFullYear()==arr[0] && date.getMonth()==arr[1]-1 && date.getDate()==arr[2]){
return true;
}
}
//dd-mm-yyyy || dd/mm/yyyy
if(arr[2].length==4){
var date = new Date(arr[2],arr[1]-1,arr[0]);
if(date.getFullYear()==arr[2] && date.getMonth()==arr[1]-1 && date.getDate()==arr[0]){
return true;
}
}
//mm-dd-yyyy || mm/dd/yyyy
if(arr[2].length==4){
var date = new Date(arr[2],arr[0]-1,arr[1]);
if(date.getFullYear()==arr[2] && date.getMonth()==arr[0]-1 && date.getDate()==arr[1]){
return true;
}
}

return false;
}
alert(IsDate("2008-02-28"));
alert(IsDate("02/30/2008"));
</script>

比较大小
<SCRIPT LANGUAGE="JavaScript">
<!--
function chechDate(){
var checkStartDate = "2009-02-01";
var checkEndDate = "2009-01-05";
var arys1= new Array();
var arys2= new Array();
if(checkStartDate != null && checkEndDate != null) {
arys=checkStartDate.split('-');
var sdate=new Date(arys[0],parseInt(arys[1]-1),arys[2]);
arys=checkEndDate.split('-');
var edate=new Date(arys[0],parseInt(arys[1]-1),arys[2]);
if(sdate > edate) {
alert("日期开始时间大于结束时间");
}else
alert("日期开始时间小于结束时间");
}
}
//-->
</SCRIPT>

你可能感兴趣的:(日期函数)