Difference between dates in JavaScript

后端 未结 8 2399
渐次进展
渐次进展 2020-11-22 13:22

How to find the difference between two dates?

8条回答
  •  时光说笑
    2020-11-22 14:00

    I have found this and it works fine for me:

    Calculating the Difference between Two Known Dates

    Unfortunately, calculating a date interval such as days, weeks, or months between two known dates is not as easy because you can't just add Date objects together. In order to use a Date object in any sort of calculation, we must first retrieve the Date's internal millisecond value, which is stored as a large integer. The function to do that is Date.getTime(). Once both Dates have been converted, subtracting the later one from the earlier one returns the difference in milliseconds. The desired interval can then be determined by dividing that number by the corresponding number of milliseconds. For instance, to obtain the number of days for a given number of milliseconds, we would divide by 86,400,000, the number of milliseconds in a day (1000 x 60 seconds x 60 minutes x 24 hours):

    Date.daysBetween = function( date1, date2 ) {
      //Get 1 day in milliseconds
      var one_day=1000*60*60*24;
    
      // Convert both dates to milliseconds
      var date1_ms = date1.getTime();
      var date2_ms = date2.getTime();
    
      // Calculate the difference in milliseconds
      var difference_ms = date2_ms - date1_ms;
    
      // Convert back to days and return
      return Math.round(difference_ms/one_day); 
    }
    
    //Set the two dates
    var y2k  = new Date(2000, 0, 1); 
    var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
    var today= new Date();
    //displays 726
    console.log( 'Days since ' 
               + Jan1st2010.toLocaleDateString() + ': ' 
               + Date.daysBetween(Jan1st2010, today));
    

    The rounding is optional, depending on whether you want partial days or not.

    Reference

提交回复
热议问题