A Simple dateDiff() Function

There is no reason to write a function for each date/time interval; one function can contain all of the required intervals and return the correct value for the one we want. In the following function, the datepart argument tells it what interval we are after, where 'w' is a week, 'd' a day, 'h' hours, 'n' for minutes, and 's' for seconds:

// datepart: 'y', 'm', 'w', 'd', 'h', 'n', 's'
Date.dateDiff = function(datepart, fromdate, todate) { 
  datepart = datepart.toLowerCase(); 
  var diff = todate - fromdate; 
  var divideBy = { w:604800000, 
                   d:86400000, 
                   h:3600000, 
                   n:60000, 
                   s:1000 }; 
  
  return Math.floor( diff/divideBy[datepart]);
}
//Set the two dates
var y2k  = new Date(2000, 0, 1);
var today= new Date();
console.log('Weeks since the new millenium: ' + Date.dateDiff('w', y2k, today)); //displays 625