javascriptstrapi

How to filter between two dates with Strapi REST API


I have entities with start_date and end_date fields. I would like to filter the entities so that only those with today's date falling between start_date and end_date are returned. The date fields are in YYYY-MM-DD format. How can I achieve this using a query?


Solution

  • I am doing something similar where I take my start_date and end_date, and check if it falls between the 01.07.2024. and 31.07.2024.

    Your requirement is a bit obscure, but it sounds like you need the $between filter, you can read more about it here.

    Try doing something like this:

    $or: [
      {
        start_date: {
          $between: [firstDayOfMonth.toISOString(), lastDayOfMonth.toISOString()],
        },
      },
      {
        end_date: {
          $between: [firstDayOfMonth.toISOString(), lastDayOfMonth.toISOString()],
        },
      },
    ];
    

    And the firstDayOfMonth and lastDayOfMonth can look something like:

    const firstDayOfMonth = new Date(2024, 7, 1, 0, 0, 0, 0);
    const lastDayOfMonth = new Date(2024, 7 + 1, 0, 23, 59, 59, 999);
    

    Hope this helps...