Find weekly periods (starting on a Monday) for a month

前端 未结 3 1389
南方客
南方客 2020-12-09 14:13

I\'m trying to find the weekly periods for a given month and year. Dates should start on a Monday and end on a Sunday. If the 1st of the month is a Sunday (Ex May 2011), it

3条回答
  •  旧巷少年郎
    2020-12-09 14:50

    If you need all weeks for selected month, and all dates for selected week, then this is all you need:

    function getWeekDays($month, $year)
    {
        $p = new DatePeriod(
            DateTime::createFromFormat('!Y-n-d', "$year-$month-01"),
            new DateInterval('P1D'),
            DateTime::createFromFormat('!Y-n-d', "$year-$month-01")->add(new DateInterval('P1M'))
        );
    
        $datesByWeek = array();
        foreach ($p as $d) {
            $dateByWeek[ $d->format('W') ][] = $d;
        }
        return $dateByWeek;
    }
    

    getWeekDays() function returns multi dimension array. first key is week number. 2 level is array, that has dates saved as DateTime object.

    Fetch example:

    print_r( getWeekDays(5, 2011) ); # May 2011
    print_r( getWeekDays(9, 2012) ); # Sep 2012
    

    I had a little time extra, so I written an example ;-)

    $datesByWeek = getWeekDays(8, 2012);
    $o = '';
    $o.= '';
    foreach ($datesByWeek as $week => $dates) {
        $firstD = $dates[0];
        $lastD = $dates[count($dates)-1];
    
        $o.= "";
        $o.= "";
        $N = $firstD->format('N');
        for ($i = 1; $i < $N; $i++) {
            $o.= "";
        }
        foreach ($dates as $d) {
            $o.= "";
                # for selected date do you magic
        }
        $N = $lastD->format('N');
        for ($i = $N; $i < 7; $i++) {
            $o.= "";
        }
        $o.= "";
    }
    $o.= '
    WeekMondayTuesdayWednesdayThursdayFridaySaturdaySunday
    " . $firstD->format('M d') . ' - ' . $lastD->format('M d') . "-" . $d->format('d.') . " / 0.00-
    '; echo $o;

    Output looks like: enter image description here

提交回复
热议问题