Search code examples
javascriptdatestring-comparison

How does JavaScript compare Date strings?


When comparing two strings, like so:

'03-15-2019' < '03-16-2019'

I get a value of true, which is what I expect.

I'm curious to learn a little more about how this works though. Is this doing a comparison of two dates, or is there some other comparison going on that I don't quite see?


Solution

  • Date strings are just strings so they obey javascript string comparison rules.

    console.log('04-13-2019' < '04-15-2019') #true
    

    But be careful here because if you rely on this comparison because if the two strings are not of the same length, it will result in unexpected behaviors like this:

    console.log('ab' < 'b') #true
    

    If you want to compare dates, you would better rely on Date object or use moment js