skip to Main Content

{

//Check if the events are happening today

  const isEventHappeningToday = events => {
    const today = dayjs().startOf('day')
    for (const event of events) {
      const eventDate = dayjs(event.date.seconds * 1000).startOf('day')

      if (eventDate.isSame(today, 'day') && event.status === 'active') {
        return true
      }
    }

    return false
  }
//return
{isEventHappeningToday ? (
          <div className='badge badge-secondary'>Happening Today!</div>
        ) : null}

}

Result-
Each and every events are now happening today. Have to make ‘Happening Today!’ show up to only events which are happening to today’s date. How do i do this?

2

Answers


  1. You can do like this:

    const todayEvents = events.filter((event) => {
      const today = dayjs().startOf("day");
      const eventDate = dayjs(event.date.seconds * 1000).startOf("day");
      return eventDate.isSame(today, "day") && event.status === "active";
    });
    
    return (
      <div className="events">
        {todayEvents.map((event) => (
          <div className="event" key={event.id}>
            <div className="badge badge-secondary">Happening Today!</div>
            <h3>{event.title}</h3>
            <p>{event.description}</p>
          </div>
        ))}
      </div>
    );
    
    Login or Signup to reply.
  2. To check if events are happening today in a .jsx file, you need to use JavaScript’s Date object to compare the current date with the date of the events. Here’s an example of how you can accomplish this:

    // Assuming you have an array of events with their respective dates
    const events = [
      {
        name: "Event 1",
        date: new Date(2023, 6, 1), // Note: month is zero-based (0 - 11)
      },
      {
        name: "Event 2",
        date: new Date(2023, 6, 2),
      },
      // ... add more events
    ];
    
    // Get the current date
    const today = new Date();
    
    // Filter events happening today
    const eventsToday = events.filter((event) => {
      // Compare the year, month, and day of the event with today's date
      return (
        event.date.getFullYear() === today.getFullYear() &&
        event.date.getMonth() === today.getMonth() &&
        event.date.getDate() === today.getDate()
      );
    });
    
    // Print the events happening today
    eventsToday.forEach((event) => {
      console.log(event.name);
    });
    

    In the above example, we create an array events that contains objects with name and date properties. We then create a new Date object today to represent the current date. We use the filter method to iterate through the events array and compare each event’s date with today’s date. The events happening today are stored in the eventsToday array, which you can then use as needed.

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