如何在JavaScript中比较月份和年份?



我需要比较日期。如输入日期大于当前下个月。在JavaScript中使用正常日期

//comparison_date is date which is current date + one month
// 14/07/2022 + One Month
input_date : 14/07/2022
comparison_date : 14/08/2022
if(input_date> comparison_date){
// false
}

input_date : 14/08/2022
comparison_date : 14/08/2022
if(input_date> comparison_date){
// false
}
input_date : 14/09/2022
comparison_date : 14/08/2022
if(input_date> comparison_date){
// true
}
input_date : 22/12/2022
comparison_date : 14/01/2023
if(input_date> comparison_date){
// false
}

你可以这样做

const toDate = dateString => {
const [day, month, year] = dateString.split('/')
return new Date(`${year}-${month}-01 00:00:00`)
}

console.log(toDate('14/07/2022') > toDate('14/08/2022'))
console.log(toDate('14/08/2022') > toDate('14/08/2022'))
console.log(toDate('14/09/2022') > toDate('14/08/2022'))
console.log(toDate('22/12/2022') > toDate('14/01/2023'))

如果你只需要比较年份和月份,你也可以做一些更简单的事情,像这样

const toYearMonth = stringDate => {
const [_, month, year] = stringDate.split('/')

return Number(`${year}${month}`)
}
console.log(toYearMonth('14/07/2022') > toYearMonth('14/08/2022'))
console.log(toYearMonth('14/08/2022') > toYearMonth('14/08/2022'))
console.log(toYearMonth('14/09/2022') > toYearMonth('14/08/2022'))
console.log(toYearMonth('22/12/2022') > toYearMonth('14/01/2023'))

文本不按日期进行比较,您需要转换为时间戳并比较值,Date类将为您完成此操作

const date1 = new Date("2022-07-14");
const date2 = new Date("2022-08-14");
console.log(date1.getTime() > date2.getTime());
console.log(date1.getTime() => date2.getTime());
console.log(date1.getTime() < date2.getTime());
console.log(date1.getTime() >= date2.getTime());
console.log(date1.getTime() == date2.getTime());

假设您想要当前日期+一个月,您可以执行

current = new Date();
nextMonth = current.setMonth(current.getMonth()+1);//note this changes the value of "current" 

然而,根据你想要的比较类型,你可能需要自定义比较,即日期1是午夜,情况2是午夜,这是大于还是等于一微秒?这取决于你的情况

注意:你似乎在使用en-GB日期格式,这是一个痛苦的尝试使用ISO yyyy-mm-dd,它简化了许多事情

最新更新