react-nativemomentjs

using momentjs to fetch data from backend


I am trying to fetch data from the backend that has the trip status set to "upcoming" but I want to conditionally fetch it using my current time. It should only fetch data that is max 15 minutes ahead. I have tried implementing it but i doesnt seem to work :(

const fetchUpcomingTrips = () => {

    let upcomingApiData = getTripsData?.data['upcoming'];
    if (upcomingApiData) {
      const currentTime = moment().utc(true).format('YYYY-MM-DDThh:mm:ssZ');
      const fifteenMinutesLater = moment().add(2, 'minutes');
  
      console.log(currentTime);
  
      // Filter trips that are 15 minutes away from the start time
      const upcomingTrips = upcomingApiData.filter(trip => {
        const rideStartTime = moment(trip?.ride_start_time);
       return rideStartTime.isBetween(currentTime, fifteenMinutesLater);
      });

      setUpcomingTrips(upcomingTrips);
    }
    
  };

this is how the date and time is set at the backend:

"ride_start_time": "2024-08-14T19:51:00Z"

it follows 24hr time and the timezone is UTC

I tried using momentjs and making sure my current time format matches the backend but it doesn't


Solution

  • Use standard Date objects. Create a now object and then another one 15 minutes later. Compare against a date from a backend. Something like this:

    const now = new Date()
    
    const later = new Date()
    later.setMinutes(later.getMinutes() + 15)
    
    const date = new Date("2024-08-14T19:51:00Z") 
    
    console.log(now < date && date < later)