循环时间数学错误地显示AM / PM

时间:2013-10-28 16:56:30

标签: php

在这种情况下,hours_start将是08:00:00,hours_end将是14:00:00

这是我用于生成开始和结束之间30分钟时间段列表的代码

while($row = $q->fetch()){
    $hours = $row['hours_end'] - $row['hours_start']; //amount of hours working in day
    for($i = 0; $i < $hours * 2; $i++){ // double hours for 30 minute increments
        $minutes_to_add = 1800 * $i; // add 30 - 60 - 90 etc.
        $timeslot = date('h:i:s', strtotime($row['hours_start'])+$minutes_to_add);
        echo "
        <tr>
            <td>" . date('h:i A', strtotime($timeslot)) . "</td>
        </tr>";
    }
}

这是产生:

08:00 AM
08:30 AM
09:00 AM
09:30 AM
10:00 AM
10:30 AM
11:00 AM
11:30 AM
12:00 PM
12:30 PM
01:00 AM
01:30 AM

正如你所看到的那样,它的作用是(i)预期直到它到达(应该是)1 PM然后它切换回AM。不知道这里发生了什么。

2 个答案:

答案 0 :(得分:3)

这是因为您使用$timeslot设置了h,这只是一个12小时的格式而没有附加ampm。然后采用12小时格式并通过strtotime运行它,如果上午或下午不存在,则需要24小时格式。因此,12岁之后的任何事情都会再次成为现实。

您需要使用:

$timeslot = date('H:i:s', strtotime($row['hours_start'])+$minutes_to_add);

OR

$timeslot = date('h:i:s a', strtotime($row['hours_start'])+$minutes_to_add);

答案 1 :(得分:0)

您的日期格式使用的是h,而不是H。小写h12 hour format

使用大写H代替24小时。

date('H:i A', strtotime($timeslot))