JS实现日期相加减

来源:互联网 发布:华盛顿西雅图大学知乎 编辑:程序博客网 时间:2024/04/27 19:58
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  2. <html>  
  3.  <head>  
  4.   <title> New Document </title>  
  5.   <meta name="Generator" content="EditPlus">  
  6.   <meta name="Author" content="">  
  7.   <meta name="Keywords" content="">  
  8.   <meta name="Description" content="">  
  9.   
  10.   <script type="text/javascript">  
  11.   
  12. function dateOperator(date,days,operator)  
  13.   
  14. {  
  15.   
  16.     date = date.replace(/-/g,"/"); //更改日期格式  
  17.     var nd = new Date(date);  
  18.     nd = nd.valueOf();  
  19.     if(operator=="+"){  
  20.      nd = nd + days * 24 * 60 * 60 * 1000;  
  21.     }else if(operator=="-"){  
  22.         nd = nd - days * 24 * 60 * 60 * 1000;  
  23.     }else{  
  24.         return false;  
  25.     }  
  26.     nd = new Date(nd);  
  27.   
  28.     var y = nd.getFullYear();  
  29.     var m = nd.getMonth()+1;  
  30.     var d = nd.getDate();  
  31.     if(m <= 9) m = "0"+m;  
  32.     if(d <= 9) d = "0"+d;   
  33.     var cdate = y+"-"+m+"-"+d;  
  34.     return cdate;  
  35. }  
  36.   
  37.    
  38.   
  39. //相减  
  40. alert(dateOperator("2014-01-01",1,"-")) ;  
  41. //相加  
  42. alert(dateOperator("2014-01-01",1,"+")) ;  
  43.   
  44. </script>   
  45.   
  46.   </script>  
  47.  </head>  
  48.   
  49.  <body>  
  50.     
  51.  </body>  
  52. </html> 
0 0