Skip to content

Instantly share code, notes, and snippets.

@trev
Created September 4, 2012 04:50
Show Gist options
  • Save trev/3616700 to your computer and use it in GitHub Desktop.
Save trev/3616700 to your computer and use it in GitHub Desktop.
Date comparison function
// How to refactor this bitch?
var dateCompare = function(date1, date2, operator) {
if(operator === ">") return date1.getTime() > date2.getTime();
if(operator === "<") return date1.getTime() < date2.getTime();
if(operator === "==") return date1.getTime() == date2.getTime();
//And so on and so forth with the other operators (>=, <=)
}
// Different approach but moves the conditional logic out
var dateCompare = function(date1, date2) {
return date1.getTime() - date2.getTime();
}
// And check logic from from point of call
if(dateCompare(dateobj1, dateobj2) < 0) console.log("<")
if(dateCompare(dateobj1, dateobj2) < 1) console.log("<=")
if(dateCompare(dateobj1, dateobj2) > 0) console.log(">")
if(dateCompare(dateobj1, dateobj2) > -1) console.log(">")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment