Search code examples
javascriptfunctionmathdatetimedatediff

javascript function to calculate difference in two dates, return short format, rounding to single unit


I struggled with wording the title, but basically I want a function where I can provide two dates and it would output something like: "2w" if the result was 15 days or "1y" if it was 13 months or "1m" if it was 4 or 5 weeks. Preferably down to the hour... but 1 day minimum.

I found a similar SO question but it's for PHP and isn't complete anyway: How to calculate the difference between two days as a formatted string?


Solution

  • There are a number of javascript date libraries out there that will do all you want and more. Here is an example using XDate

    <div id="result"><div/>
    
    var now = new XDate();
    
    var then = new XDate(2013, 04, 01, 0, 0, 0, 0);
    
    document.getElementById("result").textContent = now.diffWeeks(then).toFixed(1) + " Weeks";
    

    Available of jsfiddle

    Here is with Moments.js

    <div id="result"><div/>
    
    var then = moment("Dec 25, 1995");
    
    document.getElementById("result").textContent = moment(then, "YYYYMMDD").fromNow();
    

    also vailable on jsfiddle