resident0
resident0

Reputation: 35

Testing for the first weekday of the month in PHP

I'm working on a scheduling function to handle repeating events in an application. One option is 'Every First Weekday' (of the month). I have a function that is working, but I'm afraid I may not be using the most efficient method and was hoping for some input. I'm using PHP 5.5. This is the code I have:

function isFirstWeekday($dateObject){
  $dayToTest = $dateObject->format('l');
  $monthToTest = $dateObject->format('F Y');
  $priorDay = clone $dateObject;
  $priorDay->modify('- 1 day');
  $weekdayList = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday");
  //Return false if it's not a weekday
  if (!in_array($dateObject->format('l'), $weekdayList)) {
    return FALSE;
  }
  //Make sure that this weekday is the first of its name in the month
  if ($dateObject->format('Y-m-d') !== date('Y-m-d', strtotime("first $dayToTest of $monthToTest"))) {
    return FALSE;
  }
  //Make sure that the day before was not a weekday in the same month
  if (in_array($priorDay->format('l'), $weekdayList) && $priorDay->format('m') === $dateObject->format('m')) {
    return FALSE;
  }
  return TRUE;
}

Upvotes: 2

Views: 222

Answers (1)

rjdown
rjdown

Reputation: 9227

I would look at it another way.

1) In order for it to be the first weekday, it must be the first, second or third day of the month.

2) If it's the first day, you can directly check if it's a weekday (N = 1-5).

3) If it's the second or third, then in order to be the first weekday, the proceeding days must have NOT been week days. So just check if it's a Monday.

function isFirstWeekday($dateObject) {
    switch($dateObject->format('j')) {
        case 1:
            return $dateObject->format('N') <= 5;
        case 2:
        case 3:
            return $dateObject->format('N') == 1;
        default:
            return false;
    }
}

Upvotes: 1

Related Questions