How to find date difference in javascript

藏色散人
Release: 2021-11-15 11:20:09
Original
2610 people have browsed it

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.

How to find date difference in javascript

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>
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!