You are here

function date_repeat_set_month_day in Date 7

Same name and namespace in other branches
  1. 5.2 date_repeat/date_repeat_calc.inc \date_repeat_set_month_day()
  2. 6.2 date_repeat/date_repeat_calc.inc \date_repeat_set_month_day()
  3. 6 date_repeat/date_repeat_calc.inc \date_repeat_set_month_day()
  4. 7.3 date_repeat/date_repeat_calc.inc \date_repeat_set_month_day()
  5. 7.2 date_repeat/date_repeat_calc.inc \date_repeat_set_month_day()

Set a date object to a specific day of the month.

Example, date_set_month_day($date, 'Sunday', 2, '-') will reset $date to the second to last Sunday in the month. If $day is empty, will set to the number of days from the beginning or end of the month.

1 call to date_repeat_set_month_day()
_date_repeat_calc in date_repeat/date_repeat_calc.inc
Private implementation of date_repeat_calc().

File

date_repeat/date_repeat_calc.inc, line 470
Code to compute the dates that match an iCal RRULE.

Code

function date_repeat_set_month_day($date_in, $day, $count = 1, $direction = '+', $timezone = 'UTC') {
  if (is_object($date_in)) {
    $current_month = date_format($date_in, 'n');

    // Reset to the start of the month.
    // We should be able to do this with date_date_set(), but
    // for some reason the date occasionally gets confused if run
    // through this function multiple times. It seems to work
    // reliably if we create a new object each time.
    $datetime = date_format($date_in, DATE_FORMAT_DATETIME);
    $datetime = substr_replace($datetime, '01', 8, 2);
    $date = new DateObject($datetime, $timezone);
    if ($direction == '-') {

      // For negative search, start from the end of the month.
      date_modify($date, '+1 month');
    }
    else {

      // For positive search, back up one day to get outside the
      // current month, so we can catch the first of the month.
      date_modify($date, '-1 day');
    }
    if (empty($day)) {
      date_modify($date, $direction . $count . ' days');
    }
    else {

      // Use the English text for order, like First Sunday
      // instead of +1 Sunday to overcome PHP5 bug, (see #369020).
      $order = date_order();
      $step = $count <= 5 ? $order[$direction . $count] : $count;
      date_modify($date, $step . ' ' . $day);
    }

    // If that takes us outside the current month, don't go there.
    if (date_format($date, 'n') == $current_month) {
      return $date;
    }
  }
  return $date_in;
}