在php中获取给定月份和年份的星期分隔数组

时间:2018-01-19 06:32:36

标签: php arrays multidimensional-array

您好我正在从表单中收集月份和年份,并希望生成一个特定月份的日期数量数组,假设sunday为周开始的几周。

例如,如果输入为month=Januaryyear=2018,则所需的结果为

$array_of_dates =Array ( [Week 1] => '01/01/2018',.....,'06/01/2018'
                         [Week 2] => '07/01/2018',.....,'13/01/2018' 
                         [Week 3] => '14/01/2018',.....,'20/01/2018'
                         [Week 4] => '21/01/2018',.....,'27/01/2018' 
                         [Week 5] => '28/01/2018',.....,'31/01/2018' ) 

我试过这个

function weeks_in_month($month, $year) {
   $start = mktime(0, 0, 0, $month, 1, $year);
   $end = mktime(0, 0, 0, $month, date('t', $start), $year);
   $start_week = date('W', $start);
   $end_week = date('W', $end);

if ($end_week < $start_week) { // Month wraps
  return ((52 + $end_week) - $start_week) + 1;
}

return ($end_week - $start_week) + 1;
}

但这只给了我那个月的周数。

1 个答案:

答案 0 :(得分:2)

我会使用DateTime类作为便利方法,例如format来增加天数,function weeks_in_month($month, $year) { $dates = []; $week = 1; $date = new DateTime("$year-$month-01"); $days = (int)$date->format('t'); // total number of days in the month $oneDay = new DateInterval('P1D'); for ($day = 1; $day <= $days; $day++) { $dates["Week $week"] []= $date->format('d/m/Y'); $dayOfWeek = $date->format('l'); if ($dayOfWeek === 'Saturday') { $week++; } $date->add($oneDay); } return $dates; } print_r(weeks_in_month(1, 2018)); 来获取一个月内的总天数以及相应的日期一周。

演示:https://3v4l.org/IKGMG

Array
(
    [Week 1] => Array
        (
            [0] => 01/01/2018
            [1] => 02/01/2018
            [2] => 03/01/2018
            [3] => 04/01/2018
            [4] => 05/01/2018
            [5] => 06/01/2018
        )

    [Week 2] => Array
        (
            [0] => 07/01/2018
            [1] => 08/01/2018
            [2] => 09/01/2018
            [3] => 10/01/2018
            [4] => 11/01/2018
            [5] => 12/01/2018
            [6] => 13/01/2018
        )

    [Week 3] => Array
        (
            [0] => 14/01/2018
            [1] => 15/01/2018
            [2] => 16/01/2018
            [3] => 17/01/2018
            [4] => 18/01/2018
            [5] => 19/01/2018
            [6] => 20/01/2018
        )

    [Week 4] => Array
        (
            [0] => 21/01/2018
            [1] => 22/01/2018
            [2] => 23/01/2018
            [3] => 24/01/2018
            [4] => 25/01/2018
            [5] => 26/01/2018
            [6] => 27/01/2018
        )

    [Week 5] => Array
        (
            [0] => 28/01/2018
            [1] => 29/01/2018
            [2] => 30/01/2018
            [3] => 31/01/2018
        )

)
<span class="select">
  <%= f.date_select :date_of_birth, date_separator: '</div><div class="select">' %>
</div>