Testing for the first weekday of the month in PHP

时间:2015-10-30 23:57:06

标签: 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; }

1 个答案:

答案 0 :(得分:1)

我会以另一种方式看待它。

1)为了使它成为第一个工作日,它必须是该月的第一天,第二天或第三天。

2)如果是第一天,你可以直接检查它是否是工作日(N = 1-5)。

3)如果它是第二个或第三个,那么为了成为第一个工作日,过程日必须不是工作日。所以,检查它是否是星期一。

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;
    }
}