Home >Web Front-end >JS Tutorial >js string date direct comparison size
I encountered a bug today. A project that had been running for a year suddenly had an error in date comparison. Finally, it was found that the reason was the direct comparison of string dates.
Let’s go directly to the debugging results:
Many people say that js string dates can be compared directly, which is more intelligent
alert("2016-10-01" > "2016-10-02");// false
//No matter whether the js is compared in time format or string format, the return value is false
, so it can be compared
, but when the string date is irregular, for example:
alert("2016 -10-4" > "2016-10-30");//true
//Here js treats it as a string comparison, so it cannot be compared directly and needs to be converted into a date format
var date1 = new Date("2016-10-4");
var date2 = new Date("2016-10-10");
alert(date1> date2);//false
yy/mm/dd The format of the string date is also the same