簡體   English   中英

在開始日期到結束日期之間需要幫助

[英]Need help with looping through start-end date

我有一個包含開始和結束日期的活動日歷,如下所示:

16.08.2010 12:00:00 : 21.08.2010 20:00:00
16.08.2010 20:00:00 : 21.08.2010 23:00:00
18.08.2010 17:00:00 : 18.08.2010 19:00:00

每當活動持續一天以上時,我就需要遍歷每一天。

我找到了這個帖子,我想可以幫到我: 如何找到兩個指定日期之間的日期?

我無法使用PHP 5.3的解決方案,因為我的服務器運行PHP 5.2。
其他解決方案不會產生輸出。

這是我嘗試做的:

$events = $data['events']; 

foreach($ev as $e) :

  $startDate  =  date("Y-m-d",strtotime( $e->startTime ));
  $endDate    =  date("Y-m-d",strtotime( $e->endTime ));

  for($current = $startDate; $current <= $endDate; $current += 86400) {
      echo '<div>'.$current.' - '.$endDate.' - '.$e->name.'</div>';
  } 
endforeach;

從理論上講,對於持續數天的事件,這應該貫穿整天。 但那並沒有發生。

某個地方的邏輯是錯誤的。...請幫助:)

問題是您要在字符串中添加數字。 date('Ym-d')產生類似2011-01-31的字符串。 添加數字不會[按預期]: '2011-01-31' + 86400 = ?

嘗試以下方法:

// setting to end of final day to avoid glitches in end times
$endDate = strtotime(date('Y-m-d 23:59:59', strtotime($e->endTime)));
$current = strtotime($e->startTime);

while ($current <= $endDate) {
    printf('<div>%s - %s - %s</div>', date('Y-m-d', $current), date('Y-m-d', $endDate), $e->name);
    $current = strtotime('+1 day', $current);
}

日期(“Ymd”)錯誤,您需要在for循環中使用strtotime結果。 試試這個,它應該工作:

$events = array(
    array('16.08.2010 12:00:00', '21.08.2010 20:00:00', 'event1'),
    array('16.08.2010 20:00:00', '21.08.2010 23:00:00', 'event2'),
    array('18.08.2010 17:00:00', '18.08.2010 19:00:00', 'event3'),
);

$dayLength = 86400;
foreach($events as $e) :

  $startDate  =  strtotime( $e[0] );
  $endDate    =  strtotime( $e[1] );

  if(($startDate+$dayLength)>=$endDate) continue;

  for($current = $startDate; $current <= $endDate; $current += $dayLength) {
      echo '<div>'.date('Y-m-d', $current).' - '.date('Y-m-d', $endDate).' - '.$e[2].'</div>';
  }

endforeach;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM