Home > Mobile >  How compare array of dates with an date string to find count of same days in JavaScript?
How compare array of dates with an date string to find count of same days in JavaScript?

Time:02-12

I tried this method to check duplicate date in the array with date string array, but didn't work Please anyone can help..

    const dateArray = ["2000-07-13","03/24/2000", "June 7 2021"]
    const compaingDate =new Date("2000-06-13")
    let countOfDays=0
    for(let sameDate of dateArray){
        if(compaingDate.getDate()===sameDate.getDate()){
            countOfDays =1
        }
    }
    console.log(countOfDays);

CodePudding user response:

You never convert the array of strings into an array of dates:

    const dateArray = ["2000-07-13","03/24/2000", "June 7 2021", "June 13 2006"]
    const compaingDate =new Date("2000-06-13")
    let countOfDays=0
    for(let sameDate of dateArray){
    sameDate = new Date(sameDate)
        if(compaingDate.getDate()===sameDate.getDate()){
            countOfDays =1
        }
    }
    console.log(countOfDays);

CodePudding user response:

Maybe this is what you are looking for?

A shorten version:

const dateArray = ["2000-07-13", "03/24/2000", "June 7 2021"]
const compaingDate = new Date("2000-06-13")
let countOfDays = 0
dateArray.forEach(item => {
  if (new Date(item).getDate() === compaingDate.getDate())
    countOfDays  
})
console.log(countOfDays);

  • Related