简体   繁体   English

在开始日期到结束日期之间需要帮助

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

I have an event calendar with start and end date like this: 我有一个包含开始和结束日期的活动日历,如下所示:

16.08.2010 12:00:00 - 21.08.2010 20:00:00 16.08.2010 12:00:00 : 21.08.2010 20:00:00
16.08.2010 20:00:00 - 21.08.2010 23: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 18.08.2010 17:00:00 : 18.08.2010 19:00:00

Whenever an event goes on for more than one day, I need to loop through each day. 每当活动持续一天以上时,我就需要遍历每一天。

I found this thread, and I thought is could help me: How to find the dates between two specified date? 我找到了这个帖子,我想可以帮到我: 如何找到两个指定日期之间的日期?

I can't use the solution for PHP 5.3, because my server run PHP 5.2. 我无法使用PHP 5.3的解决方案,因为我的服务器运行PHP 5.2。
The other solutions do not procude output. 其他解决方案不会产生输出。

This is what I try to do: 这是我尝试做的:

$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;

In theory, this should loop through all days for an event that extends over several days. 从理论上讲,对于持续数天的事件,这应该贯穿整天。 But that's not happening. 但那并没有发生。

The logic is wrong somewhere.... please help :) 某个地方的逻辑是错误的。...请帮助:)

The problem is that you're trying to add numbers to a string. 问题是您要在字符串中添加数字。 date('Ym-d') produces a string like 2011-01-31 . date('Ym-d')产生类似2011-01-31的字符串。 Adding numbers to it won't work [as expected]: '2011-01-31' + 86400 = ? 添加数字不会[按预期]: '2011-01-31' + 86400 = ? .

Try something along these lines: 尝试以下方法:

// 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);
}

The date("Ymd") is wrong, you need the strtotime Result in your for loop. 日期(“Ymd”)错误,您需要在for循环中使用strtotime结果。 Try this, it should work: 试试这个,它应该工作:

$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