You are here

function date_plus_period in Date 5

Compute min and max dates for a P value

@value = an argument in the format (start date)P#(period type) where (period type) can be Y (year), M (month), D (day), W (week), H (hour) i.e. P1Y or P90D or P1Y3M2D4H

Return value

an array of ISO dates representing the first and last day in the range

1 call to date_plus_period()
date_views_date_range in ./date_views.inc

File

./date_views.inc, line 481

Code

function date_plus_period($value) {
  include_once drupal_get_path('module', 'date_api') . '/date.inc';

  // min date is whatever is to the left of the period sign, defaults to current date
  $value = str_replace('--P', 'P', $value);
  $range = explode('P', $value);
  $min_date = date_range_value($range[0], 'min');

  // create a date object to use for the max_date
  $max_date = date_make_date($min_date, 'GMT', 'db', DATE_ISO);

  // iterate through the requested period, adding values as needed to the date object
  $remaining = $range[1];
  if ($years = strpos($remaining, 'Y')) {
    $sub = explode('Y', $remaining);
    $remaining = $sub[1];
    $count = intval($sub[0]);
    $max_iso = intval(substr($max_date->db->iso, 0, 4) + $count) . substr($max_date->db->iso, 4, 15);
    date_set_date($max_date, $max_iso, 'GMT', 'db', DATE_ISO, TRUE);
  }
  if ($months = strpos($remaining, 'M')) {
    $sub = explode('M', $remaining);
    $remaining = $sub[1];
    $count = intval($sub[0]);
    $cur_mon = intval(substr($max_date->db->iso, 5, 2));
    $cur_year = intval(substr($max_date->db->iso, 0, 4));
    $max_iso = (intval($cur_mon + $count) < 13 ? $cur_year : intval($cur_year + 1)) . '-' . sprintf('%02d', intval($cur_mon + $count) < 13 ? intval($cur_mon + $count) : 1) . substr($min_date, 7, 12);
    date_set_date($max_date, $max_iso, 'GMT', 'db', DATE_ISO, TRUE);
  }
  if (stristr($range[1], 'W')) {
    $sub = explode('W', $remaining);
    $remaining = $sub[1];
    $count = intval($sub[0]);
    $max_unix = intval($max_date->db->timestamp + 604800 * $count);
    date_set_date($max_date, $max_unix, 'GMT', 'db', DATE_UNIX, TRUE);
  }
  if ($days = strpos($remaining, 'D')) {
    $sub = explode('D', $remaining);
    $remaining = $sub[1];
    $count = intval($sub[0]);
    $max_unix = intval($max_date->db->timestamp + 86400 * $count);
    date_set_date($max_date, $max_unix, 'GMT', 'db', DATE_UNIX, TRUE);
  }
  if ($hours = strpos($remaining, 'H')) {
    $sub = explode('H', $remaining);
    $remaining = $sub[1];
    $count = intval($sub[0]);
    $max_unix = intval($max_date->db->timestamp + 3600 * $count);
    date_set_date($max_date, $max_unix, 'GMT', 'db', DATE_UNIX, TRUE);
  }

  // slice 1 second off max date to stop it just before end of period
  // needed because we are using <= as the operator
  $date->db->unix = intval($max_date->db->timestamp - 1);
  date_set_date($max_date, $date->db->unix, 'GMT', 'db', DATE_UNIX, TRUE);
  return array(
    $min_date,
    $max_date->db->iso,
  );
}