Difference between two dates in years, months, days in JavaScript

前端 未结 26 3021
执念已碎
执念已碎 2020-11-22 07:18

I\'ve been searching for 4 hours now, and have not found a solution to get the difference between two dates in years, months, and days in JavaScript, like: 10th of April 201

26条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 07:57

    Actually, there's a solution with a moment.js plugin and it's very easy.

    You might use moment.js

    Don't reinvent the wheel again.

    Just plug Moment.js Date Range Plugin.


    Example:

    var starts = moment('2014-02-03 12:53:12');
    var ends   = moment();
    
    var duration = moment.duration(ends.diff(starts));
    
    // with ###moment precise date range plugin###
    // it will tell you the difference in human terms
    
    var diff = moment.preciseDiff(starts, ends, true); 
    // example: { "years": 2, "months": 7, "days": 0, "hours": 6, "minutes": 29, "seconds": 17, "firstDateWasLater":  false }
    
    
    // or as string:
    var diffHuman = moment.preciseDiff(starts, ends);
    // example: 2 years 7 months 6 hours 29 minutes 17 seconds
    
    document.getElementById('output1').innerHTML = JSON.stringify(diff)
    document.getElementById('output2').innerHTML = diffHuman
    
    
    
      
    
      
    
    
    
      
      

    Difference between "NOW and 2014-02-03 12:53:12"


提交回复
热议问题