'check min date and max date using javascript
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 }
Solution 1:[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');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |