问题
If I start with the current date, how can I get the first Friday of each month?
I was thinking about using $date->get(Zend::WEEKDAY) and comparing that to Friday and then with DAY and checking if it is less than or equal to 7. Then adding 1 month onto it.
There must be something simpler?
回答1:
How about
$firstFridayOfOcober = strtotime('first friday of october');
Or turn it into a handy function:-
/**
* 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");
}
You could use this with Zend_Date like this:-
$zDate = new Zend_Date();
$zDate->setTimestamp(firstFriday('october'));
Then Zend_Debug::dump($zDate->toString());
will produce :-
string '7 Oct 2011 00:00:00' (length=19)
I'd say that's a lot simpler :)
Edit after some more thought:
A more generalised function may be of more use to you, so I'd suggest using this:-
/**
* 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;
}
These days my preferred method is to extend PHP's 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);
Gives:-
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)
来源:https://stackoverflow.com/questions/7699529/first-day-of-each-month