温馨提示×

PHP中怎么判断当天时间段

PHP
小亿
99
2024-01-19 13:54:31
栏目: 编程语言

要判断当天的时间段,可以使用PHP中的时间函数来获取当前时间,并进行判断。下面是一个示例代码:

<?php
$current_time = strtotime(date('H:i')); // 获取当前时间的时间戳
$morning_start = strtotime('06:00'); // 早上开始时间
$noon_start = strtotime('12:00'); // 中午开始时间
$afternoon_start = strtotime('13:00'); // 下午开始时间
$evening_start = strtotime('18:00'); // 晚上开始时间

if ($current_time >= $morning_start && $current_time < $noon_start) {
    echo "早上";
} elseif ($current_time >= $noon_start && $current_time < $afternoon_start) {
    echo "中午";
} elseif ($current_time >= $afternoon_start && $current_time < $evening_start) {
    echo "下午";
} else {
    echo "晚上";
}
?>

在上面的代码中,我们使用strtotime函数将时间字符串转换为时间戳,并使用date函数获取当前时间的小时和分钟部分。然后,我们比较当前时间的时间戳与预定义的时间段的时间戳来判断当前时间属于哪个时间段,并输出相应的结果。

注意,上述代码只是一个示例,你可以根据自己的需求来定义时间段的开始和结束时间。

0