Skip to content

hook_civicrm_relativeDate

Deprecated Hook

This hook is deprecated as of CiviCRM 6.20 and will be removed around 6.32. Use hook_civicrm_relativeDateSql instead.

In CiviCRM 6.20+, returning date values from this hook emits an E_USER_DEPRECATED warning. This hook only supported static PHP date strings (Ymd), which cannot be used to generate dynamic MySQL Views in SearchKit and are less efficient than native SQL date expressions.

Summary

Allows extensions to define custom relative date filters by returning an array with from and to date values.

Replacement

Please use hook_civicrm_relativeDateSql, which returns native MySQL expressions and supports Search, Reports, Mailing, APIv4, and SearchKit MySQL Views.

If your filter is just adding a longer interval to an existing filter you may not need the hook. See Adding New Filters in the user guide.

Definition

hook_civicrm_relativeDate($filter)

Parameters

  • string $filter: the relative date filter that has been added to the option group relative_date_filters.

Returns

  • array: An associative array with from and to keys representing the start and end dates formatted as Ymd strings.

Availability

  • Available since CiviCRM 6.5.
  • Deprecated since CiviCRM 6.20.

Examples

(Legacy example for reference. For new implementations, use hook_civicrm_relativeDateSql.)

Here is a simple example, assuming your extension is called myextension and that the values ccourse and pcourse have been added to the option group relative_date_filters:

/**
 * Implements hook_civicrm_relativeDate().
 *
 * @deprecated since 6.20. Use hook_civicrm_relativeDateSql instead.
 *
 * Allows extensions to define custom relative date filters by returning a date range.
 *
 * @param string $filter
 *   The relative date filter that has been added to the option group `relative_date_filters`
 */
function myextension_civicrm_relativeDate($filter) {
  $dates = [];
  $today = new DateTime();
  $currentMonth = (int)$today->format('n');

  $courseStartYear = ($currentMonth >= 9) ? (int)$today->format('Y') : (int)$today->format('Y') - 1;

  if ($filter == 'ccourse') {
    $startYear = $courseStartYear;
    $endYear = $courseStartYear + 1;

    $dates['from'] = (new DateTime("{$startYear}-09-01"))->format('Ymd');
    $dates['to'] = (new DateTime("{$endYear}-08-31"))->format('Ymd');
  }

  if ($filter == 'pcourse') {
    $startYear = $courseStartYear - 1;
    $endYear = $courseStartYear;

    $dates['from'] = (new DateTime("{$startYear}-09-01"))->format('Ymd');
    $dates['to'] = (new DateTime("{$endYear}-08-31"))->format('Ymd');
  }

  return $dates;
}