查找特定月份和年份的星期日期范围

时间:2016-07-03 07:07:08

标签: php

假设我有可用的日期:2016-07

我想找到这样的周日期范围:

    2016-07-03 to 2016-07-09
    2016-07-10 to 2016-07-16
    2016-07-17 to 2016-07-23
    2016-07-24 to 2016-07-30

我怎样才能做到这一点? 我尝试使用MySql但失败了。现在我正在尝试php

2 个答案:

答案 0 :(得分:1)

这段代码应该完全符合您的要求,如果没有,请告诉我或您是否有疑问

$date = "2016-07"; //Your date, can be any given date of this format
$monthAndYear = explode("-", $date);

$weeks = array();

$start = mktime(0, 0, 0, $monthAndYear[1], 1, $monthAndYear[0]);
$start -= 86400; //There are surely better ways

//find beginning if first week
do
{
    $start += 86400;// Add one day
    $tmp = date("N", $start);
}
while($tmp != 1);

//Get all weeks. If you want only those which are in the current month use this instead:
//while(date("n", ($start + 6 * 86400)) == $monthAndYear[1])
while(date("n", $start) == $monthAndYear[1])
{
    $date = date("Y-m-d", $start);
    $start += (6 * 86400);
    $date .= " to ".date("Y-m-d", $start);
    $weeks[] = $date;
    $start += 86400;
}

echo "<pre>";
var_dump($weeks);
echo "</pre>";

输出是这样的:

array(4) {
  [0]=>
  string(24) "2016-07-04 to 2016-07-10"
  [1]=>
  string(24) "2016-07-11 to 2016-07-17"
  [2]=>
  string(24) "2016-07-18 to 2016-07-24"
  [3]=>
  string(24) "2016-07-25 to 2016-07-31"
}

使用第二个while选项,结果将是相同的,因为第31个月是月末,也是一周结束。

答案 1 :(得分:0)

请尝试以下代码,它会产生与您相同的输出:

function weeksRangesOfMonth($month, $year) {

    $start_time = mktime(0, 0, 0, $month, 1, $year);
    $start_time = mktime(0, 0, 0, $month, date('d', strtotime('First Monday', $start_time)), $year);

    $end_time = mktime(0, 0, 0, $month, date('t', $start_time), $year);

     $start = date("Y-m-d", $start_time);
     $end = date("Y-m-d", $end_time);

     for($date = $start; $date <= $end; $date = date('Y-m-d', strtotime($date. ' + 7 days'))) {

        $time=  strtotime($date);

        $from = date("Y-m-d", strtotime('Last Sunday', $time));
        $to = date("Y-m-d", strtotime('Next Saturday', $time));

        echo "Start: ".$from.", End: ".$to;
        echo "<br>";
    }
}

weeksRangesOfMonth(7, 16);

演示: enter image description here