skip to Main Content

I want to compare each of the dates that come from that array and compare them with today’s date, if there is a date that is equal to today’s date, let {showImage} be true:

   data: [
        {
            id: "1",
            date: "2021-10-05T00:00:00.000Z"
        },
        {
            id: "2",
            date: "2021-10-06T00:00:00.000Z"
        }
]

  const [showImage, setShowImage] = useState(false)

How can I make this comparison?

Note: I only want the date I don’t care about the time.

2

Answers


  1.   const [showImage, setShowImage] = useState(false)
       data: [
            {
                id: "1",
                date: "2021-10-05T00:00:00.000Z"
            },
            {
                id: "2",
                date: "2021-10-06T00:00:00.000Z"
            }
    ]
    
      const [showImage, setShowImage] = useState(false)
     const [extra, setExtra] = useState(0)
    
    React.useEffect(()=>{
    
    
    
    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
    var yyyy = today.getFullYear();
    
    let todayDate = yyyy+ '-' + mm+ '-' + dd; you get the current date
    
    let filterData=data.filter(dateVal=>{
        
       if(dateVal.date.slice(0,10) == todayDate){
           return
                {
                 setShowImage(true)
                 setExtra(extra+1) 
                }
       else
                {
           return
                {
                 setShowImage(true)
                 setExtra(extra+1) 
                 }   
                }
    
    })
    },[])
    
    Login or Signup to reply.
  2. First make the substring and get only date from whole date object then loop over the data and compare the data date to today date here is the my approach any correction is welcome:

      let data=[
        {
            id: "1",
            date: "2022-07-29T00:00:00.000Z"
        },
        {
            id: "2",
            date: "2021-10-06T00:00:00.000Z"
        }
    ]
    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
    var yyyy = today.getFullYear();
    
     today = yyyy + '-' + mm + '-' + dd;
    
     data.map((item)=>{
        console.log(item.date.slice(0,10).toString() == today.toString(),"checking")
        if(item.date.slice(0,10).toString() == today.toString()){
          // setImage(true)
          }else{
          // do anything
          }
     })
    

    you can run this code in useeffect to achieve what you want.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search