2017-09-05 132 views
1

我希望用戶能夠選擇日期範圍和時間間隔以顯示結果,例如「顯示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日,它仍包括所有的日期在一月。

理想的情況下它會顯示:

  • 日:2017年1月8日; 2017年1月9日; ... 2017年1月19日; 2017年1月20日
  • 星期:2017年1月8日; 2017年1月15日
  • 月份:一月,2017年

如何做到這一點有什麼建議?謝謝!

+0

任何特別的原因,爲什麼你不希望設置'$ start'和'$ end'到選擇的開始和結束日期? – Aydin4ik

+0

@Aydin不是真的,我對DateTime對象不是很熟悉,所以我將代碼從另一個類似的線程中解除。我試圖刪除修改部分,但遇到了一個錯誤,所以我放棄了這個想法。這樣做確實讓我更接近了,儘管我在2017年8月7日 - 2017年9月7日進行了一項測試,測試時間間隔爲一個月,而我只有8月份回來 - 而不是9月份。任何想法爲什麼? – Matt

回答

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

相關問題