0

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);
James
  • 2,732
  • 2
  • 5
  • 28
Nagaraj
  • 31
  • 7
  • You need to convert `sameDate` to a `Date` object. – 001 Feb 11 '22 at 16:00
  • 1
    Do you want to compare just the day of the month or the whole date? [MDN getDate](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDate) – Louys Patrice Bessette Feb 11 '22 at 16:07
  • Re `new Date("2000-06-13")`, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Feb 11 '22 at 20:24

2 Answers2

0

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

Coder Gautam YT
  • 1,044
  • 7
  • 20
  • Parsing arbitrary timestamps with the built–in parser is not a good idea, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Feb 11 '22 at 20:25
0

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);
James
  • 2,732
  • 2
  • 5
  • 28