找到两个日期之间不同长度的时间间隔

时间:2017-09-05 04:55:01

标签: php date datetime intervals

我希望用户能够选择日期范围和间隔来显示结果,例如“显示2017年1月1日到2017年4月1日之间的结果,按天|周|月列出”

因此,如果他们选择了一天,我会在2017年1月1日之前将结果分组; 2017年1月2日; 2017年1月3日;等...

如果他们选择了一周,那就是2017年1月1日; 2017年1月8日; 2017年1月15日;等...

我现在使用的方法如下:

if(isset($chosenInterval) && ($chosenInterval == "week" || $chosenInterval == "day") ) {
    $timeFormat = "F j, Y"; 
} else {
    $timeFormat = "F Y";
    $chosenInterval = "month";
}

$start    = (new DateTime($start))->modify('first day of this month');
$end      = (new DateTime($stop))->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 '.$chosenInterval);
$period   = new DatePeriod($start, $interval, $end);

foreach($period as $dt) {
    $dataLabels[] = $dt->format($timeFormat);
}   

问题是如果用户选择2017年1月8日 - 2017年1月20日,它仍然包括1月份的所有日期。

理想情况下会显示:

  • 日:2017年1月8日; 2017年1月9日; 2017年1月19日; 2017年1月20日
  • 周:2017年1月8日; 2017年1月15日
  • 月:2017年1月

有关如何完成此任务的任何建议?谢谢!

1 个答案:

答案 0 :(得分:0)

如果日期在开始之前或结束之后,您需要检查何时将DateTime对象添加到$dataLabels。如果是(并且$chosenInterval不是一个月),请不要添加它们:

<?php
$start = "2017-01-08";
$stop = "2017-01-20";
$chosenInterval = "week";
function getDates($start, $stop, $chosenInterval = "week") {
    $startDT = new DateTime($start); // make a DateTime out of the date to later compare it
    $stopDT = new DateTime($stop); // make a DateTime out of the date to later compare it
    if(isset($chosenInterval) && ($chosenInterval == "week" || $chosenInterval == "day") ) {
        $timeFormat = "F j, Y"; 
    } else {
        $timeFormat = "F Y";
        $chosenInterval = "month";
    }

    $begin    = (new DateTime($start))->modify('first day of this month');
    $end      = (new DateTime($stop))->modify('first day of next month');
    $interval = DateInterval::createFromDateString('1 '.$chosenInterval);
    $period   = new DatePeriod($begin, $interval, $end);

    foreach($period as $dt) {
        if ($chosenInterval !== "month" && ($dt < $startDT || $dt > $stopDT)) continue; // if date is before start or after end, skip
        $dataLabels[] = $dt->format($timeFormat);
    }
    return $dataLabels;
}
var_dump(getDates($start, $stop));
var_dump(getDates($start, $stop, "day"));
var_dump(getDates($start, $stop, "month"));

Demo

相关问题