Home > Web Front-end > JS Tutorial > How to find date difference in javascript_javascript skills

How to find date difference in javascript_javascript skills

WBOY
Release: 2016-05-16 15:12:30
Original
1858 people have browsed it

The example in this article describes how to find the date difference in JavaScript. Share it with everyone for your reference, 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 the 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

Readers who are interested in more JavaScript-related content can check out the special topics on this site: "Summary of JavaScript search algorithm techniques", "Summary of JavaScript animation special effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm techniques", "Summary of JavaScript traversal algorithms and techniques" and "JavaScript Mathematics Summary of operation usage

I hope this article will be helpful to everyone in JavaScript programming.

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