查找给定日期是否是该月的第一个星期一

时间:2013-09-18 15:53:57

标签: php function date datetime

尝试传递一些验证以检查给定日期是否是该月的第一个星期一,如果是,那么如果不执行其他操作则执行某些操作。到目前为止,我已经想出了这个来检查一周的日期,但是不知道如何检查它是否是该月的第一个星期一,最好是我希望这个功能。

$first_day_of_week = date('l', strtotime('9/2/2013'));
// returns Monday

2 个答案:

答案 0 :(得分:3)

尝试一下:

$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.
}

我知道,似乎有点像asinine,但如果需要,它允许你用变量替换'9/2/2013'

答案 1 :(得分:1)

您可以使用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

相关问题