【问题标题】:Need help with looping through start-end date在循环开始结束日期方面需要帮助
【发布时间】:2011-01-30 23:57: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
18.08.2010 17:00:00 - 18.08.2010 19:00:00

每当一个事件持续超过一天时,我就需要每天循环播放。

我找到了这个帖子,我认为它可以帮助我:How to find the dates between two specified date?

我无法使用 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;

理论上,对于持续数天的事件,这应该循环所有天。 但这并没有发生。

逻辑有问题....请帮忙:)

【问题讨论】:

    标签: php datetime


    【解决方案1】:

    问题是您正在尝试将数字添加到字符串中。 date('Y-m-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);
    }
    

    【讨论】:

      【解决方案2】:

      日期(“Y-m-d”)是错误的,你需要在你的 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;
      

      【讨论】:

      • 好吧,我的速度不够快... :)
      猜你喜欢
      • 1970-01-01
      • 2023-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多