Home > Article > Web Front-end > How to find date difference in javascript
How to find the date difference in javascript: 1. Create an HTML sample file; 2. Convert the two dates into timestamps; 3. Then divide by the number of milliseconds in each day to get the number of days apart.
The operating environment of this article: windows7 system, javascript version 1.8.5, DELL G3 computer
How to find the date difference with javascript?
How to find the date difference in javascript
The details are as follows:
<script type="text/javascript"> function daytonow(year, month, date){ //思路就是转换两个日期为时间戳即毫秒数,再除以每一天的毫秒数得出相隔多少天 //JS中的month是从0开始,所以month要减一 month--; //过去的日子 var tdate = new Date(year, month, date).getTime(); //今天 var tnow = new Date().getTime(); var longdate = Math.ceil((tnow - tdate) / (1000 * 60 * 60 * 24)); return longdate; } alert(daytonow(2009, 4, 5)); </script>
The difference in days between two dates:
//两日期串的天数之差, 前-后, sDate1-sDate2 function DateDiff(sDate1, sDate2) { //sDate1和sDate2是"2002-12-18"格式 var aDate, oDate1, oDate2, iDays; aDate = sDate1.split("-"); oDate1 = new Date(aDate[0], aDate[1] - 1, aDate[2]); aDate = sDate2.split("-"); oDate2 = new Date(aDate[0], aDate[1] - 1, aDate[2]); iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); if ((oDate1 - oDate2) < 0) { return -iDays; } return iDays; } //两日期串的天数之差, 前-后, sDate1-sDate2 function DateDiff2(sDate1, sDate2) { //sDate1和sDate2是"12/18/2011"格式 var oDate1, oDate2, iDays; oDate1 = new Date(sDate1); oDate2 = new Date(sDate2); var iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); if ((oDate1 - oDate2) < 0){ return -iDays; } return iDays; }
Recommended study: "javascript basic tutorial"
The above is the detailed content of How to find date difference in javascript. For more information, please follow other related articles on the PHP Chinese website!