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!

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.