简体   繁体   English

使用 javascript 检查最小日期和最大日期

[英]check min date and max date using javascript

Having to dates like this '2022-04-30' & '2022-05-30'必须像这样的“2022-04-30”和“2022-05-30”这样的日期

using javascript how can evaluate which dates is lower?使用 javascript 如何评估哪些日期较低? I tried to convert them to milliseconds but with this format date I dont know how我试图将它们转换为毫秒,但我不知道如何使用这种格式的日期

example例子

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

// true } // 真的 }

EDIT: As pointed out by @RobG the dates are in the ISO format so there is no need for dates at all:编辑:正如@RobG所指出的,日期采用 ISO 格式,因此根本不需要日期:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM