一尘不染

PHP获取每月的星期数

php

所以我有一个脚本,可以返回特定月份和年份中的星期数。我该如何从该月开始的某一天,确定是该月的第1,2,3,4或5周的一部分?


阅读 300

收藏
2020-05-26

共1个答案

一尘不染

我尝试过的最令人沮丧的事情-就是这里!

<?php

    /**
     * Returns the amount of weeks into the month a date is
     * @param $date a YYYY-MM-DD formatted date
     * @param $rollover The day on which the week rolls over
     */
    function getWeeks($date, $rollover)
    {
        $cut = substr($date, 0, 8);
        $daylen = 86400;

        $timestamp = strtotime($date);
        $first = strtotime($cut . "00");
        $elapsed = ($timestamp - $first) / $daylen;

        $weeks = 1;

        for ($i = 1; $i <= $elapsed; $i++)
        {
            $dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
            $daytimestamp = strtotime($dayfind);

            $day = strtolower(date("l", $daytimestamp));

            if($day == strtolower($rollover))  $weeks ++;
        }

        return $weeks;
    }


    //
    echo getWeeks("2011-06-11", "sunday"); //outputs 2, for the second week of the month
?>
2020-05-26