简体   繁体   中英

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 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 <= $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 . 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("Ymd") 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM