繁体   English   中英

如果今天的日期在12月1日至1月5日之间

[英]IF todays date is between 1st December and 5th January

尝试编写一个IF语句以显示圣诞节的开放时间,使用的公式是:今天的日期在12月1日至1月5日之间,否则显示正常时间。 但是我得到的只是平时。

$xmasStart = date('m-d', strtotime('11-01'));
$xmasEnd = date('m-d', strtotime('01-05'));
if((date('m-d') > $xmasStart) && (date('m-d') < $xmasEnd)) {
    echo 'Christmas Opening Hours';
} else {
    echo '<p class="marginbottom0">Monday to Friday: 8am - 6pm<br><small>Saturday &amp; Sunday: Appointment only</small></p>';
}

不要使用字符串进行日期数学运算。 使用更清晰易懂的DateTime()

DateTime()对象具有可比性,因此您无需将它们转换为字符串即可进行比较。 此外,它还了解时区和夏令时(此处不起作用,但有时您可以使用日期)。

<?php

$xmasStart = new DateTime('11/1 00:00:00');
$xmasEnd = new DateTime('1/5 23:59:59');
$now = new DateTime();
if($now >= $xmasStart && $now < $xmasEnd) {
    echo 'Christmas Opening Hours';
} else {
    echo '<p class="marginbottom0">Monday to Friday: 8am - 6pm<br><small>Saturday &amp; Sunday: Appointment only</small></p>';
}

此外,我将时间添加为每天的DateTime, strtottime()将使用当前时间,而不是每天的开始或结束,因此在圣诞节时间的最后一天,您将不会显示正确的时间。 (您也可以将最后一天更改为1/6 00:00:00 )。

演示版

strtotime无法理解您的短时间定义,请尝试使用Ymd格式的完整日期(分别为2017-12-012018-01-05 )。 另请注意,您的比较不包括边缘日期,因此您可能要使用<=>=代替。

$xmasStart = date('Y-m-d', strtotime('2017-12-01'));
$xmasEnd = date('Y-m-d', strtotime('2018-01-05'));
$now = date('Y-m-d');
if(($now >= $xmasStart) && ($now <= $xmasEnd)) {
    echo 'Christmas Opening Hours';
} else {
    echo '<p class="marginbottom0">Monday to Friday: 8am - 6pm<br><small>Saturday &amp; Sunday: Appointment only</small></p>';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM