1

我有一个函数可以在两个时间标记之间创建时间间隔。该功能有效,但我正在努力升级strtotime()和使用该DateTime课程。

下面是我写的一段代码没有出错

$timestart = new DateTime("14:00:00");
$timestop = new DateTime("20:00:00");
$date_diff = $timestop->diff($timestart);
$time_diff = $date_diff->format('%H');

接下来是原封不动的整个代码。我DateInterval could not be converted to int使用上面的代码出错了。请告知如何正确实施课程。

现场示例:http ://codepad.org/jSFUxAnp

function timemarks() 
    {       

        //times are actually retrieved from db
        $timestart = strtotime("14:00:00");
        $timestop = strtotime("20:00:00");

        $time_diff = $timestop - $timestart; //time difference

        //if time difference equals negative value, it means that $timestop ends second day 
        if ($time_diff <= 0) 
        {
            $timestop = strtotime( '+1 day' , strtotime( $row->timestop ) ); //add 1 day and change the timetsamp
            $time_diff = $timestop - $timestart;
        }

        //create interval
        $split = 3;
        $interval = $time_diff/$split;

        //get all timemarks
        $half_interval = $interval / 2;
        $mid = $timestart + $half_interval;     
        for ( $i = 1; $i < $split; $i ++) {
            //round intervals   
            $round_mid = round($mid / (15 * 60)) * (15 * 60);
            $result .= date('H:i:s', $round_mid) . ", ";
            $mid += $interval;
        }       
        $round_mid = round($mid / (15 * 60)) * (15 * 60);
        $result .= date('H:i:s', $round_mid);

        return $result;
    } 

输出15:00:00, 17:00:00, 19:00:00

4

1 回答 1

2

实际上你正在使用 DateTime,这些只是创建 DateTime 实例的别名

等效项如下所示:

$timestart = new DateTime("14:00:00");
$timestop = new DateTime("20:00:00");
$date_diff = $timestop->diff($timestart);
$time_diff = $date_diff->format('%H');

所以这必须工作,我测试了它,我得到了正确的结果!

于 2012-06-17T01:37:46.953 回答