Nifty JavaScript Date Comparison
Comparing dates and times in JavaScript is pretty simple really. The following little code snippet illustrates how simple it really is:
/* Returns the number of minutes between the two dates.
* Understanding the result:
* - If less than zero then dateB is earlier than dateA.
* - If zero then the dates are the same.
* - If greater than zero then dateA is early than dataB.
*/
function compareDates(dateA, dateB ) {
var difference = 0,
_dateB = new Date(dateB ),
_dateA = new Date(dateA);
difference = _dateB - _dateA;
return Math.round(difference/(1000*60)); // compute minutes
}
There isn't much to elaborate on this topic...it's pretty straight forward. This is a helpful function that is worth adding to any JavaScript utility file.
Happy coding!
Comments