Home > Enterprise >  How to compare month and year in JavaScript?
How to compare month and year in JavaScript?

Time:07-15

i need to compare date.like input date is greater than current next month.using normal date in 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
    }

CodePudding user response:

you can do something like this

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

if you just need to compare year and month you can also do something more simple like this

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

CodePudding user response:

Text doesn't compare datewise, you need to convert to a timestamp and compare the values, the Date class would do this for you

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

assuming you want the current date one month you can do

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

however depending on the type of compare you want you may need to customise the compare, ie date one is midnight case 2 is midnight and a microsecond is this greater than or equal? depends on your situation

note: you appear to be using the en-GB date format which is a pain try to use ISO yyyy-mm-dd, it simplifies many things

  • Related