使用的是my97datepicker插件,选择日期时触发onpicked对应方法:calRange(dom1, dom2, dom3)。其中dom1是开始日期input对应id,dom2是结束日期input对应id,dom3是需要显示相差天数的span。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 6 <title>js计算两个日期相差天数</title> 7 <link href="datepicker/skin/WdatePicker.css" rel="stylesheet" type="text/css"> 8 <script src="jquery-1.11.1.min.js"></script> 9 <script src="datepicker/WdatePicker.js"></script> 10 <style> 11 * { 12 padding: 0; 13 margin: 0; 14 } 15 .content { 16 padding: 10px; 17 width: 400px; 18 height: 400px; 19 border: 1px dashed #ccc; 20 } 21 .content div:last-child { 22 margin-top: 40px; 23 } 24 .form-control { 25 display: inline-block; 26 width: 33%; 27 padding: 6px 12px; 28 font-size: 14px; 29 line-height: 1.42857143; 30 color: #555; 31 vertical-align: middle; 32 background-color: #fff; 33 border-bottom: 1px solid #ccc; 34 border-radius: 4px; 35 -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075); 36 box-shadow: inset 0 1px 1px rgba(0,0,0,.075); 37 -webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s; 38 -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; 39 transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; 40 } 41 .m-span { 42 display: inline-block; 43 margin: 0 4%; 44 width: 8%; 45 text-align: center; 46 vertical-align: middle; 47 } 48 </style> 49 </head> 50 <body> 51 <div class="content"> 52 <div> 53 <input class="form-control Wdate" id="startDate" type="text" onfocus="WdatePicker({dateFmt: 'yyyy/MM/dd', maxDate:'#F{$dp.$D(\'endDate\')||\'new Date()\'}', onpicked: function(){calRange('#startDate', '#endDate', '#dateRange')}})" placeholder="开始日期" autocomplete="off"> 54 <span class="m-span">--</span> 55 <input class="form-control Wdate" id="endDate" type="text" onfocus="WdatePicker({dateFmt: 'yyyy/MM/dd', minDate:'#F{$dp.$D(\'startDate\')}', onpicked: function(){calRange('#startDate', '#endDate', '#dateRange')}})" placeholder="结束日期" autocomplete="off"> 56 </div> 57 <div>相差天数:<span id="dateRange"></span></div> 58 </div> 59 <script> 60 function calRange(dom1, dom2, dom3){ 61 var startDate = $(dom1).val(), endDate = $(dom2).val(); 62 if(startDate.length > 0 && endDate.length > 0){ 63 var start_date = new Date(startDate); 64 var end_date = new Date(endDate); 65 var days = (end_date - start_date)/86400000; 66 $(dom3).text(days + "天"); 67 } else { 68 $(dom3).text(0 + "天"); 69 } 70 } 71 </script> 72 </body> 73 </html>
效果截图: