开发者

Need help with looping through start-end date

开发者 https://www.devze.com 2023-02-07 08:40 出处:网络
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 20:00:00 - 21.08.2010 23:00:00

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 20:00:00 - 21.08.2010 23: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.

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 <= $endDa开发者_运维百科te; $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('Y-m-d') produces a string like 2011-01-31. Adding numbers to it won't work [as expected]: '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("Y-m-d") is wrong, you need the strtotime Result in your for loop. 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消