Search code examples
datejs

How do I work out how many days ago date1 was compared to date2, using datejs?


var d1 = Date.parse(date); // eg, 7th jan
var d2 = Date.today(); // eg, 2nd jan

I want to do:

(d2 - d1).days

which with the above data, should return 5.

Is this possible with datejs?


Solution

  • The optional TimeSpan module includes functionality to easily get various value differences between two date objects.

    http://code.google.com/p/datejs/source/browse/trunk/src/time.js

    Just include after your main date.js include, or combine.

    In the "time.js" file, there's also a TimePeriod class. You might not require, so just crop what you need if weight is an issue.

    The following sample demonstrates the full scenario.

    Example

    var d1 = Date.parse("jan 7"); // eg, 7th jan
    var d2 = Date.parse("jan 2"); // eg, 2nd jan
    
    console.log(new TimeSpan(d1 - d2).days); // 5
    

    Hope this helps.