js实现日期的相加减

时间:2023-03-09 07:34:25
js实现日期的相加减
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content=""> <script type="text/javascript"> function dateOperator(date,days,operator) { date = date.replace(/-/g,"/"); //更改日期格式
var nd = new Date(date);
nd = nd.valueOf();
if(operator=="+"){
nd = nd + days * 24 * 60 * 60 * 1000;
}else if(operator=="-"){
nd = nd - days * 24 * 60 * 60 * 1000;
}else{
return false;
}
nd = new Date(nd); var y = nd.getFullYear();
var m = nd.getMonth()+1;
var d = nd.getDate();
if(m <= 9) m = "0"+m;
if(d <= 9) d = "0"+d;
var cdate = y+"-"+m+"-"+d;
return cdate;
} //相减
alert(dateOperator("2014-01-01",1,"-")) ;
//相加
alert(dateOperator("2014-01-01",1,"+")) ; </script> </script>
</head> <body> </body>
</html>