1

Having to dates like this '2022-04-30' & '2022-05-30'

using javascript how can evaluate which dates is lower ? I tried to convert them to milliseconds but with this format date I dont know how

example

if('2022-04-30' < '2022-05-30') {

// true }

Jose A.
  • 483
  • 2
  • 7
  • 15
  • Does this answer your question? [Min/Max of dates in an array?](https://stackoverflow.com/questions/7143399/min-max-of-dates-in-an-array) – Lluís Muñoz Apr 29 '22 at 14:29
  • `if ('2022-04-30' < '2022-05-30')` is fine, ISO 8601 format date strings are designed to compare correctly as strings. If you *really* want to convert to number (millisecond offset), then `Date.parse('2022-04-30') < date.parse('2022-05-30')` works too, provided the strings are in a format supported by ECMA-262 (which the OP strings are). :-) – RobG May 02 '22 at 03:50

1 Answers1

1

EDIT: As pointed out by @RobG the dates are in the ISO format so there is no need for dates at all:

if ('2022-04-30' < '2022-05-30')
  console.log('true')

However this does not work with other date formats, for example:

if ('30-04-2022' < '30-05-2020')
  console.log('returns true, but is incorrect')
  
if (new Date('30-04-2022') < new Date('30-05-2020'))
  console.log('returns false')

ORIGINAL ANSWER: You are trying to compare strings not dates. Try this:

const date1 = new Date('2022-04-30');
const date2 = new Date('2022-05-30');

if (date1 < date2) {
  console.log('true');
}

Or shorter:

if (new Date('2022-04-30') < new Date('2022-05-30'))
  console.log('true');
Samball
  • 623
  • 7
  • 22
  • "*You are trying to compare strings not dates*" is not a problem. ISO 8601 dates compare as strings, so no need for Dates at all. `'2022-04-30' < '2022-05-30'` returns *true*, as it should. – RobG May 02 '22 at 03:46