0

trying to pass in some validation to check if a given date is the first monday of the month, if it is then do something if not do something else. So far I have come up with this to check the day of week given a date but dont know how to check if it is the first monday of the month, preferably I would like to make this a function.

$first_day_of_week = date('l', strtotime('9/2/2013'));
// returns Monday
  • Check out [Getting first weekday in a month with strtotime](http://stackoverflow.com/questions/4357490/getting-first-weekday-in-a-month-with-strtotime), here on SO! – Marty McVry Sep 18 '13 at 15:57
  • Kindly refer to this: http://stackoverflow.com/questions/14063336/php-how-to-use-timestamp-to-check-if-today-is-monday-or-1st-of-the-month – aaron Sep 18 '13 at 16:00

2 Answers2

3

Give this a try:

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

It seems kind of asinine, I know, but it allows you to replace '9/2/2013' with a variable if needed.

theftprevention
  • 5,083
  • 3
  • 18
  • 31
1

You could use the DateTime classes to do this very easily:-

/**
 * 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));

See it working.

vascowhite
  • 18,120
  • 9
  • 61
  • 77