如何使用mysql获取当月的每周开始日期和结束日期?

时间:2018-02-13 18:53:36

标签: mysql date

我希望结果如下: -

|----------------------------------------------|
| Week Number |   start date  |    end date    |
|----------------------------------------------|
|      1      |   2018-02-01  |    2018-02-04  |
|----------------------------------------------|
|      2      |   2018-02-05  |    2018-02-11  |
|----------------------------------------------|
|      3      |   2018-02-12  |    2018-02-18  |
|----------------------------------------------|
|      4      |   2018-02-19  |    2018-02-25  |
|----------------------------------------------|
|      5      |   2018-02-26  |    2018-02-28  |
|----------------------------------------------|

因为,2018年2月的第一天是星期四,第一周是1到4(星期日)。

我有一个查询,它给出了到目前为止所有周的开始日期和结束日期。

$currentWeekData = $this->CustomerPayment->query('SELECT WEEK(CURDATE()) AS current_week');
$currentWeek = $currentWeekData[0][0]['current_week'];
for($w = 0; $w <= $currentWeek; $w++)
{
    $flagPay = 0;
    $flagDep = 0;
    $actualWeek = intval($w + 1);
    $currentYear = date('Y');
    $currentYearFirstDay = $currentYear.'-01-01';
    $queryWeekRange = "SELECT '$currentYearFirstDay'+INTERVAL ($actualWeek-WEEK('$currentYearFirstDay', 1))*7 - WEEKDAY('$currentYearFirstDay') DAY as start_date,'$currentYearFirstDay'+INTERVAL ($actualWeek-WEEK('$currentYearFirstDay', 1)+1)*7-1 - WEEKDAY('$currentYearFirstDay') DAY as end_date";
    $resultWeekRange = $this->CustomerPayment->query($queryWeekRange);
}

但我希望查询仅列出当前月份的每周范围。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

我必须同意@schwern,你真的需要在数据库中这样做吗?这在PHP中会更有效率。确实除了更多的行(但我怀疑一个相当简单的MySQL查询实际上可以实现你所要求的)。

我会在PHP中做过类似的事情(但我不保证这是最有效的方式)。

$currentMonth = 12; //Could be date("n") or 1-12
$currentYear = date('Y'); //Could also be any year
$firstDate = strtotime("$currentYear-$currentMonth-1");
$lastDate = strtotime(date('Y-m-t', $firstDate));
$isLastDayPassed = false;
$loopingDate = $firstDate;
$weeks = [];
$weekNumber = 1;
while(!$isLastDayPassed){
    if(date("n", $loopingDate) != $currentMonth){
        $isLastDayPassed = true;
        continue;
    }
    $firstDayOfWeek = date('w', $loopingDate) == 1 ? date('Y-m-d', $loopingDate) : date('Y-m-d', $loopingDate);
    $lastDayOfWeek = date("n", strtotime("next sunday", $loopingDate)) == $currentMonth ? date('Y-m-d', strtotime("next sunday", $loopingDate)) : date('Y-m-d', $lastDate);

    $weeks[] = [
        "start_date" => $firstDayOfWeek,
        "end_date" => $lastDayOfWeek,
        "week_number" => $weekNumber
    ];
    $loopingDate = strtotime("next monday", $loopingDate);
    $weekNumber++;
}