[removed] Calculate difference between two dates

前端 未结 4 1726
温柔的废话
温柔的废话 2021-01-15 03:23

I want to find difference between two Dates. For that I did subtract one Date object from another Date object. My code is as follows :

var d1 = new Date(); /         


        
相关标签:
4条回答
  • 2021-01-15 03:48

    If you need to be fairly accurate I suggest using days as your unit. Years have a variable number of days so do months, so saying "1 month" or "1 year" can mean different #s of days.

    var d1 = new Date(); //"now"
    var d2 = new Date(2012,3,17); // before one year
    var msPerDay = 1000*60*60*24;
    document.write( ((d1 - d2) / msPerDay).toFixed(0) + " days ago");
    
    0 讨论(0)
  • 2021-01-15 03:57

    So fundamentally the biggest exact date unit is a week which accounts for 7 * 86400 seconds. Months and Years are not exaclty defined. So assuming you want to say "1 Month ago" if the two dates are e.g. 5.1.2013 and 5.2.2013 or 5.2.2013 and 5.3.2013. And saying "1 Month and 1 day ago" if you have e.g. 5.1.2013 and 6.2.2013, then you would have to use a calculation like this:

    // dateFrom and dateTo have to be "Date" instances, and to has to be later/bigger than from.
    function dateDiff(dateFrom, dateTo) {
      var from = {
        d: dateFrom.getDate(),
        m: dateFrom.getMonth() + 1,
        y: dateFrom.getFullYear()
      };
    
      var to = {
        d: dateTo.getDate(),
        m: dateTo.getMonth() + 1,
        y: dateTo.getFullYear()
      };
    
      var daysFebruary = to.y % 4 != 0 || (to.y % 100 == 0 && to.y % 400 != 0)? 28 : 29;
      var daysInMonths = [0, 31, daysFebruary, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    
      if (to.d < from.d) {
        to.d   += daysInMonths[parseInt(to.m)];
        from.m += 1;
      }
      if (to.m < from.m) {
        to.m   += 12;
        from.y += 1;
      }
    
      return {
        days:   to.d - from.d,
        months: to.m - from.m,
        years:  to.y - from.y
      };
    }
    // Difference from 1 June 2016 to now
    console.log(dateDiff(new Date(2016,5,1), new Date()));

    As I said, it gets tricky ;)

    0 讨论(0)
  • 2021-01-15 03:58

    Are you looking for this?

    Math.ceil((new Date(2012, 11, 23) - new Date(2012, 11, 21)) / 864000) + 1

    0 讨论(0)
  • 2021-01-15 04:03

    Are you looking for this?

     Math.ceil((new Date(2012, 11, 23) - new Date(2012, 11, 21)) / 86400000) + 1
    
    0 讨论(0)
提交回复
热议问题