Skip to main content

Entity Query: Get all the node entities between a daterange

First we have to make sure that we have the starting and ending date in the correct drupal datetime format:

use Drupal\Core\Datetime\DrupalDateTime;

  if (is_null($date)){
    // Get a date string suitable for use with entity query.
    $start = date('d-m-YT00:00:00',time());
    $end = date('d-m-YT23:59:00',time());
  }
  else {
    $start = date('d-m-YT00:00:00',strtotime($date));
    $end = date('d-m-YT23:59:00',strtotime($date));
  }

  $start_date = new DrupalDateTime($start);
  $start_date->setTimezone(new \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE));
  $start_date = $start_date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);

  $end_date = new DrupalDateTime($end);
  $end_date->setTimezone(new \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE));
  $end_date = $end_date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);

Check between all the possible date ranges:

$query = \Drupal::entityQuery('node')
        ->condition('type', 'event_programme')
        ->condition('status', 1)
        ->sort('created', 'DESC')
        ->condition('field_event_daterange.value', $start_date, '<')
        ->condition('field_event_daterange.end_value', $end_date, '>');

$result_nids = $query->execute();

$query = \Drupal::entityQuery('node')
      ->condition('type', 'event_programme')
      ->condition('status', 1)
      ->sort('created', 'DESC')
      ->condition('field_event_daterange.value', $start_date, '>=')
      ->condition('field_event_daterange.value', $end_date, '<=');
$result_nids = array_merge($result_nids,$query->execute());

$query = \Drupal::entityQuery('node')
    ->condition('type', 'event_programme')
    ->condition('status', 1)
    ->sort('created', 'DESC')
    ->condition('field_event_daterange.end_value', $start_date, '>=')
    ->condition('field_event_daterange.end_value', $end_date, '<=');

$result_nids = array_merge($result_nids,$query->execute());

 

entity query