Javascript dateDiff function

I needed a function to check the difference between 2 dates in javascript. I couldn't find a suitable one, so I created this one:

function dateDiff(datepart, fromdate, todate)// datepart: 'w', 'd', 'h', 'n', 's'
{
datepart = datepart.toLowerCase();
var diff = todate - fromdate;
var divideBy = {
w:604800000 //1000*60*60*24*7
, d:86400000 // 1000*60*60*24
, h:3600000 // 1000*60*60
, n:60000 // 1000*60
, s:1000
};
return Math.floor(diff/divideBy[datepart]);
}
del.icio.us Digg StumbleUpon Facebook Technorati Fav reddit Google Bookmarks
| Viewed 6705 times
  1. Dan G. Switzer, II

    #1 by Dan G. Switzer, II - juli 8, 2010 at 18:15

    I'd recommend actually moving the calculation to comments and hardcode the calculations for your divideBy object, this will speed things especially if this function is used a lot in your code.

    The overhead may not be much on a single call, but considering you're doing 5 calculation on each call to the function and the values don't change, it'll be more efficient to just hardcode the values and leave the equation as a comment for reference.
  2. Paul Klinkenberg

    #2 by Paul Klinkenberg - juli 9, 2010 at 13:36

    Thanks Dan, you're absolutely right! The reason why I left it with the calculations inside was "human readability", but adding those as a comment is much better, and serves the same cause.
    Regards, Paul
  3. Dave Stillman

    #3 by Dave Stillman - september 28, 2011 at 0:47

    I've been looking for a datediff function in javascript, and this is a fantastic, simple solution. Thanks for posting this.
(will not be published)
Leave this field empty