1.20.x date.inc date_range_years($string, $date = NULL)

Splits a string like -3:+3 or 2001:2010 into an array of start and end years.

Center the range around the current year, if any, but expand it far enough so it will pick up the year value in the field in case the value in the field is outside the initial range.

Parameters

string $string: A min and max year string like '-3:+1'.

object $date: (optional) A date object. Defaults to NULL.

Return value

array: A numerically indexed array, containing a start and end year.

File

includes/date.inc, line 1445
Date API functions and constants.

Code

function date_range_years($string, $date = NULL) {
  $this_year = date_format(date_now(), 'Y');
  list($start_year, $end_year) = explode(':', $string);

  // Valid patterns would be -5:+5, 0:+1, 2008:2010.
  $plus_pattern = '@[\+\-][0-9]{1,4}@';
  $year_pattern = '@^[0-9]{4}@';
  if (!preg_match($year_pattern, $start_year, $matches)) {
    if (preg_match($plus_pattern, $start_year, $matches)) {
      $start_year = $this_year + $matches[0];
    }
    else {
      $start_year = $this_year;
    }
  }
  if (!preg_match($year_pattern, $end_year, $matches)) {
    if (preg_match($plus_pattern, $end_year, $matches)) {
      $end_year = $this_year + $matches[0];
    }
    else {
      $end_year = $this_year;
    }
  }
  // If there is a current value, stretch the range to include it.
  $value_year = is_object($date) ? $date->format('Y') : '';
  if (!empty($value_year)) {
    if ($start_year <= $end_year) {
      $start_year = min($value_year, $start_year);
      $end_year = max($value_year, $end_year);
    }
    else {
      $start_year = max($value_year, $start_year);
      $end_year = min($value_year, $end_year);
    }
  }
  return array($start_year, $end_year);
}