Первый день каждого месяца - PullRequest
3 голосов
/ 09 октября 2011

Если я начну с текущей даты, как я могу получить первую пятницу каждого месяца?

Я думал о том, чтобы использовать $ date-> get (Zend :: WEEKDAY) и сравнивать его с пятницей, а затем с ДНЕМ и проверять, меньше ли оно или равно 7. Затем добавить на него 1 месяц.

Должно быть что-то попроще?

1 Ответ

5 голосов
/ 09 октября 2011

Как насчет

$firstFridayOfOcober = strtotime('first friday of october');

Или превратить его в удобную функцию: -

 /**
 * Returns a timestamp for the first friday of the given month
 * @param string $month
 * @return type int
 */
function firstFriday($month)
{
    return strtotime("first friday of $month");
}

Вы можете использовать это с Zend_Date следующим образом: -

$zDate = new Zend_Date();
$zDate->setTimestamp(firstFriday('october'));

Тогда Zend_Debug::dump($zDate->toString()); выдаст: -

string '7 Oct 2011 00:00:00' (length=19)

Я бы сказал, что это намного проще:)

Правка после еще нескольких мыслей:

Более обобщенная функция может быть более полезной для вас, поэтому я рекомендую использовать это: -

/**
 * Returns a Zend_Date object set to the first occurence
 * of $day in the given $month.
 * @param string $day
 * @param string $month
 * @param optional mixed $year can be int or string
 * @return type Zend_Date
 */
function firstDay($day, $month, $year = null)
{
    $zDate = new Zend_Date();
    $zDate->setTimestamp(strtotime("first $day of $month $year"));
    return $zDate;
}

В наши дни мой предпочтительный метод - расширение объекта PHP DateTime : -

class MyDateTime extends DateTime
{
    /**
    * Returns a MyDateTime object set to 00:00 hours on the first day of the month
    * 
    * @param string $day Name of day
    * @param mixed $month Month number or name optional defaults to current month
    * @param mixed $year optional defaults to current year
    * 
    * @return MyDateTime set to last day of month
    */
    public function firstDayOfMonth($day, $month = null, $year = null)
    {
        $timestr = "first $day";
        if(!$month) $month = $this->format('M');
        $timestr .= " of $month $year";
        $this->setTimestamp(strtotime($timestr));
        $this->setTime(0, 0, 0);
        var_dump($this);
    }
}
$dateTime = new MyDateTime();
$dateTime->firstDayOfMonth('Sun', 'Jul', 2011);

Дает: -

object(MyDateTime)[36]
  public 'date' => string '2011-07-03 00:00:00' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'UTC' (length=3)
...