PHP IF / ELSEIF / ELSE用于日期和时间

时间:2016-06-27 21:10:31

标签: php if-statement

我已经在一个小型系统上获得了一段代码,我已经将它们放在一起工作,并且几乎可以完美地工作。

这个想法是,在星期一到星期五的上午9点到下午5点之间,它会显示一个表格,在这些时间之外,它会显示一条消息,建议他们寻求其他团队的帮助。

今天似乎工作得很好,而我通过改变时间等来测试它。但是它似乎根本不想工作,我似乎通过添加&解决了它#39; 09'而不是' 9'作为开始时间,我只是检查了它正在使用的页面,并且表格在理论上显示它应该是消息。

有什么想法吗?

    <?php
date_default_timezone_set('Europe/London');

$day = date("l"); 
$current_hour = date("g"); 

if ($day == "Monday" && $current_hour >= 09 && $current_hour <= 17) { 
require_once('../forms/function.php');
formcraft(6); 
} 
elseif ($day == "Tuesday" && $current_hour >= 09 && $current_hour <= 17) { 
require_once('../forms/function.php');
formcraft(6); 
} 
elseif ($day == "Wednesday" && $current_hour >= 09 && $current_hour <= 17) { 
require_once('../forms/function.php');
formcraft(6); 
} 
elseif ($day == "Thursday" && $current_hour >= 09 && $current_hour <= 17) { 
require_once('../forms/function.php');
formcraft(6); 
} 
elseif ($day == "Friday" && $current_hour >= 09 && $current_hour <= 17) { 
require_once('../forms/function.php');
formcraft(6); 
} 
else 
{ 
     echo "We're not in the office right now. If your request is urgent, and by that we mean that it will have an immediate impact on our customers and/or people, please forward it to the Duty Managerwho'll know what to do."; 
} 
?>

2 个答案:

答案 0 :(得分:7)

您的代码,已优化:

<?php
date_default_timezone_set('Europe/London');

$day = date("w"); // Numeric representation of the day of the week
$current_hour = date("G"); // G 24-hour format of an hour without leading zeros

if ($day >= 1 && $day < 6 && $current_hour >= 9 && $current_hour <= 17)

{
    require_once ('../forms/function.php');
    formcraft(6);
}else{
    echo "We're not in the office right now. If your request is urgent, and by that we mean that it will have an immediate impact on our customers and/or people, please forward it to the Duty Managerwho'll know what to do.";
}

?>

答案 1 :(得分:3)

手写。

$dayname = date('w');
$hour = date('G');

if( $dayname >= 1 && $dayname <= 5 && $hour>=9 && $hour<=17) {
    //your code
}