Php DateTime和时间戳计算

时间:2013-08-14 10:17:38

标签: php algorithm datetime math for-loop

我正在尝试获取一系列日期来填充日历,我面临着无限循环的问题。

以下是代码:

$month_length = 1;
$day_begin = 9;
$day_end = 19;
$event_interval = 15;

$date = new DateTime();

$today_date_name = $date->format("D");
$today_date_number = $date->format("j");
$today_date_month = $date->format("M");
$today_date_month_number =$date->format("n");
$today_date_year = $date->format("Y");


for ($length = 0; $length <= ($month_length - 1); $length++)
{
    $date->modify("+$length month"); 
    $current_date_name = $date->format("D");
    $current_date_number = $date->format("j");
    $current_date_month = $date->format("M");
    $current_date_month_number = $date->format("n");
    $current_date_year = $date->format("Y");

    //calculate the length of the month
    $current_month_length = cal_days_in_month(CAL_GREGORIAN, $current_date_month_number, $current_date_year);

    if($current_date_month_number != $today_date_month_number){
        // if we are not in the current month, start the second loop
        // the first of the month.
        $current_date_number = 1;
    }

    for($current_date_number; $current_date_number <= $current_month_length; $current_date_number++)
    {
        $date->setDate($current_date_year, $current_date_month_number, $current_date_number);

        //set the ending before because of the loop;

        //set the ending of the day
        $date->setTime($day_end, 0, 0);
        //get the timestamp of beginning
        $ending_timestamp = $date->format("U");

        //set the beginning of the day
        $date->setTime($day_begin, 0, 0);
        //get the timestamp of beginning
        $beginning_timestamp = $date->format("U");

        $day_length = $ending_timestamp - $beginning_timestamp;

        //60 seconds for 1min
        $interval = 60 * $event_interval;

        for($the_timestamp = 0; $the_timestamp <= $day_length ; $the_timestamp + $interval)
        {
            $current_timestamp = $beginning_timestamp + $the_timestamp;
            $date->setTimestamp($current_timestamp);
            $final_array[$current_date_year][$current_date_number . " " . $current_date_month][$current_timestamp] = $date->format("H : i");
        }

    }
}

最后一个“for”循环以无限循环结束,因此达到最大执行时间,必须在30秒内完成。

2 个答案:

答案 0 :(得分:2)

你的代码太复杂了,你做错了什么。以下将生成一个代表整年的数组: -

$start = new \DateTime('1st January');
$end = new \DateTime('31st December');
$interval = new \DateInterval('P1D');
$period = new \DatePeriod($start, $interval, $end->modify('+ 1 day'));

$year = array();

foreach($period as $day){
    $year[$day->format('M')][(int)$day->format('d')] = $day->format('D');
}

var_dump($year);

See it working

答案 1 :(得分:1)

for($the_timestamp = 0; $the_timestamp <= $day_length ; $the_timestamp + $interval){
    //Stuff
}

此循环不会增加$the_timestamp,这就是它永远循环的原因。

最后一部分应为$the_timestamp += $interval,相当于$the_timestamp = $the_timestamp + $interval