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';

Date without year

It is not necessary to compare years. A date can simply be a month and a day:

let date1 = '12-01'; let date2 = '11-01'; console.log(date1 > date2);

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

let date1 = '09-21'; let date2 = '09-23';

Date falling into the interval

Let there be three intervals: from January 1st to March 8th, from March 9th to June 17th, from June 18th to December 31st. Suppose we also have some date containing month and day. Let's determine what period this date falls into:

let date = '08-20'; if (date >= '01-01' && date <= '03-08') { console.log('1st interval'); } if (date >= '03-09' && date <= '06-17') { console.log('2d interval'); } if (date >= '06-18' && date <= '12-31') { console.log('3d interval'); }

Given a date containing the month and day. Determine the zodiac sign that this date falls on.

enru