2011-10-08 225 views
3

如果我從當前日期開始,我怎樣才能得到每個月的第一個星期五?每個月的第一天

我正在考慮使用$ date-> get(Zend :: WEEKDAY)並將它與週五然後與DAY進行比較,並檢查它是否小於或等於7.然後將1個月添加到它。

必須有更簡單的東西?

回答

5

如何

$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 object: -

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) 
+0

感謝。 '''部分在php 5.2中工作嗎? –

+0

我看不出爲什麼不。試試吧,看看:)本頁更新日誌部分可能會有所幫助http://php.net/manual/en/function.strtotime.php – vascowhite

+0

頭腦風暴! O__O –