Strings are always compared character by character.
var bigger = "2017-01-01";
var smaller = "2000/01/01";
console.log(`'${bigger}' > '${smaller}'`, bigger > smaller);
bigger = "2000-12-01";
console.log(`'${bigger}' > '${smaller}'`, bigger > smaller);
When we compare this "2000-12-01"
to this "2000/01/01"
it seems as though it fails. But the comparison matches the first four characters '2000'
and then compares the fifth "/"
and "-"
and the "-"
has a lower ASCII value then "/"
does.
A string comparison has to check each character, one by one, until it finds a difference. If no difference it ever found then the strings are the same.
Once a difference is found that indicates which string is greater then the other.
Example:
String 1: "My dog howels"
String 2: "My dog barks"
The code checks each character until it finds a difference:
Position 0: "M" vs "M"
- Same
Position 1: "y" vs "y"
- Same
Position 2: " " vs " "
- Same
Position 3: "d" vs "d"
- Same
Position 4: "o" vs "o"
- Same
Position 5: "g" vs "g"
- Same
Position 6: " " vs " "
- Same
Position 7: "h" vs "b"
- "h"
is greater than "b"
.
So string 1 is greater then string 2.
Compare with Date Object
If you want to compare dates then it is best practice to use the date object:
var bigger = Date.parse("2017-01-01");
var smaller = Date.parse("2000/01/01");
console.log(`'${bigger}' > '${smaller}'`, bigger > smaller);
bigger = Date.parse("2000-12-01");
console.log(`'${bigger}' > '${smaller}'`, bigger > smaller);
Date.parse()
will convert your properly formatted date string into a date object and then compare the integer representation of the dates, giving accurate results.
The Date
object stores all dates as a number and numbers are must faster to compare.
Compare without Date Object
If You don't want to use a date object then you need to get rid of the separators to compare just the numbers. But this may not work if your date objects are not always two digits for month and day.
function fixDate(dateStr) {
return dateStr.replace(/[\/\-\s]/g, '');
}
var bigger = fixDate("2017-01-01");
var smaller = fixDate("2000/01/01");
console.log(`'${bigger}' > '${smaller}'`, bigger > smaller);
bigger = fixDate("2000-12-01");
console.log(`'${bigger}' > '${smaller}'`, bigger > smaller);
The replace
with the regular expression removes all '-'
, '/'
and white space from your string.
So '2018/01/11'
becomes '20180111'
and '2000-05-01'
becomes '20000501'
.
Both methods only work if your date strings are properly formatted.