【问题标题】:Find if a given date is the first monday of the month查找给定日期是否是该月的第一个星期一
【发布时间】:2013-09-18 15:53:56
【问题描述】:
试图通过一些验证来检查给定的日期是否是当月的第一个星期一,如果是,那么做一些事情,如果不是做其他事情。到目前为止,我已经想出了这个来检查给定日期的星期几,但不知道如何检查它是否是本月的第一个星期一,最好我想把它变成一个函数。
$first_day_of_week = date('l', strtotime('9/2/2013'));
// returns Monday
【问题讨论】:
标签:
php
function
date
datetime
【解决方案1】:
试试这个:
$first_day_of_week = date('l', strtotime('9/2/2013'));
$date = intval(date('j', strtotime('9/2/2013')));
if ($date <= 7 && $first_day_of_week == 'Monday') {
// It's the first Monday of the month.
}
我知道,这看起来有点笨拙,但它允许您在需要时将 '9/2/2013' 替换为变量。
【解决方案2】:
您可以使用DateTime 类非常轻松地做到这一点:-
/**
* Check if a given date is the first Monday of the month
*
* @param \DateTime $date
* @return bool
*/
function isFirstMondayOfMonth(\DateTime $date)
{
return (int)$date->format('d') <= 7 && $date->format('l') === 'Monday';
}
$day = new \DateTime('2013/9/2');
var_dump(isFirstMondayOfMonth($day));
$day = new \DateTime('2013/10/2');
var_dump(isFirstMondayOfMonth($day));
看working。