Home > Net >  how to compare an array of dates with today's date in react native?
how to compare an array of dates with today's date in react native?

Time:07-30

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)

Could you help me make this comparison? I would appreciate it

**** Note: I only want the date I don't care about the time ****

CodePudding user response:

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.

CodePudding user response:

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

})
},[])
  • Related