Bill
Bill

Reputation: 129

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?

Upvotes: 1

Views: 47

Answers (2)

Ramy M. Mousa
Ramy M. Mousa

Reputation: 5933

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

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

String comparison happens character by character

console.log('aaaa' < 'b')
console.log('aa' < 'ab')
console.log('ab' < 'aa')

'03-15-2019' < '03-16-2019' This is just string comparison not date comparison, if you want to compare dates you need to change it to date Object and than compare

console.log(new Date('03/15/2019') < new Date('03/16/2019'))

Upvotes: 1

Related Questions