算法描述
求出两个日期之间相差的毫秒数,然后除以一天的毫秒数即得到两个日期之间相差的天数。
方法
js求两个日期之间相隔天数的方法 字符串参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function daysDistance(date1, date2) { var distance, tempDate, daysApart; date1 = Date.parse(date1); date2 = Date.parse(date2); distance = date2 - date1; distance = Math.abs(distance); distance = Math.floor(distance / (24 * 3600 * 1000)); return distance; };
|
js获取当日的格式化时间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function today() { var today=new Date(); var str=""; str+=today.getFullYear()+"-"; var month=today.getMonth()+1; if(month<10) str+="0"; str+=month+"-"; var day=today.getDate(); if(day<10) str+="0"; str+=day; return str; }
|
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| <html> <head> <meta charset="utf-8"> <title></title> <script> function daysDistance(date1, date2) { var distance, tempDate, daysApart; date1 = Date.parse(date1); date2 = Date.parse(date2); distance = date2 - date1; daysApart = Math.abs(distance); daysApart = Math.floor(distance / (24 * 3600 * 1000)); return daysApart; }; function today() { var today = new Date(); var str = ""; str += today.getFullYear() + "-"; var month = today.getMonth() + 1; if (month < 10) str += "0"; str += month + "-"; var day = today.getDate(); if (day < 10) str += "0"; str += day; return str; } function show() { document.getElementById("in_output").innerText = "今天" + today() + "到2017-3-1共计:" + daysDistance("2017-3-1", today()) + "天"; } </script> </head> <body> <span id="in_output"></span> <input type="button" onclick="show()" value="显示今日到2017-3-1间隔的天数"> </body> </html>
|
显示效果: