# String comparison of dates in JavaScript

Let we have two dates in the following text format:

`let date1 = '2020-12-01'; let date2 = '2019-12-01';`

In this case, you can compare these dates and find out which of these dates is greater:

`console.log(date1 > date2); // shows true`

How are these dates compared? The point is that our dates are strings and JavaScript compares them as strings. That is, it first compares the first characters of the two dates: if they are the same, then JavaScript compares the second characters, and so on, until it finds a difference. Due to the fact that in our date format the year is first, then the month, and then the day, then such a comparison is possible.

The fact is that if the value of the first year turns out to be greater than the value of the second year, then it no longer matters what the months and days are - the first year is definitely greater. If the years coincide, then the date that has month value greater then it will be greater. And if the months coincide, then the date with the greater day value will be greater. Well, if the days are the same, then the dates are the same.

It is also important that the dates are in the same format. In our case, hyphens are separators for parts of dates. This, of course, is not required. For example, you can put dots:

`let date1 = '2020.12.01'; let date2 = '2019.12.01';`

Or remove the separators at all:

`let date1 = '20201201'; let date2 = '20191201';`

The main thing for the comparison to be correct, the placement should be as follows: first the year, then the month, then the day.

Write code that will compare the two dates below and print a message about which one is greater:

`let date1 = '2020-11-31'; let date2 = '2020-12-01';`
← →
↑
en ru