how to find the last monday of the month

前端 未结 3 609
死守一世寂寞
死守一世寂寞 2021-01-05 18:55

I\'m not sure how to go about this one. I\'m building a calendar in PHP and need users to be able to add a repeating event that follows the following rule:

Last [DOW

3条回答
  •  梦毁少年i
    2021-01-05 19:45

    I have a generic function for you to calculate the nth day of a month. Hope this could help you to resolve your issue.

    function get_Nth_dow($dow, $occurence, $m, $y)
    {
        $numdays = date('t', mktime(0, 0, 0, $m, 1, $y));
        $add = 7 * ($occurence - 1);
        $firstdow = date('w', mktime(0, 0, 0, $m, 1, $y));
        $diff = $firstdow - $dow;
    
        $day_of_month = 1;
        if ($diff > 0)
        {
            $day_of_month += ($add - $diff);
        }
        elseif ($diff < $numdays)
        {
            $day_of_month -= ($diff - $add);
        }
    
        return $day_of_month;
    }
    

    $DOW = day of the week (0 = Sunday, 6 = Saturday).

    $X = occurence (1 = first, 2 = third, etc..). If the given month does

    not have the occurrence, then it will return the last. For example, if

    you ask for the 7th occurrence of Friday, it will return the last

    Friday of the month. $M = month $Y = year

    Example, get_Nth_DOW(2,3,7,2009) will return the third Tuesday of 7th 2009.

提交回复
热议问题