Home > Web Front-end > JS Tutorial > js string date direct comparison size

js string date direct comparison size

高洛峰
Release: 2016-12-02 15:55:42
Original
2917 people have browsed it

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


Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template