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


loop with time math is incorrectly showing AM/PM

在本例中,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 点,然后切换回 AM。 不知道这里发生了什么。

这是因为您使用h设置$timeslot,该格式仅为 12 小时格式,没有附加ampm。然后采用 12 小时格式并通过 strtotime 运行它,如果不存在 am 或 pm,则需要 24 小时格式。因此,12 点之后的任何东西都会再次变成 am。

您需要使用:

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

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

您的日期格式使用的是h而不是H。小写h是 12 小时格式

改用大写H 24 小时。

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