javascript for the date difference method

  • 2021-01-19 22:01:32
  • OfStack

This article illustrates the javascript method for finding date differences. To share with you for your reference, as follows:


<script type="text/javascript">
function daytonow(year, month, date){
 // The idea is to convert the two dates into timestamps in milliseconds, divided by each 1 The number of milliseconds in days tells you how many days are apart 
 //JS In the month from 0 Here we go, so month Need to get 1
 month--;
 // Bygone days 
 var tdate = new Date(year, month, date).getTime();
 // today 
 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 of days between two dates:


// The difference in days between two date strings ,  before - after , sDate1-sDate2
function DateDiff(sDate1, sDate2) { //sDate1 and sDate2 is "2002-12-18" format 
  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;
}
// The difference in days between two date strings ,  before - after , sDate1-sDate2
function DateDiff2(sDate1, sDate2) { //sDate1 and sDate2 is "12/18/2011" format 
  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;
}

More about JavaScript related content interested readers can view the site features: "JavaScript search algorithm skills summary", "JavaScript animation effects and skills summary", "JavaScript error and debugging skills summary", "JavaScript data structure and algorithm skills summary", "JavaScript eraser algorithm and skills summary" and "JavaScript mathematical operation usage summary"

I hope this article is helpful to JavaScript program design.


Related articles: