简体   繁体   English

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

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

Trying to write an IF statement to show Christmas opening hours, using the formula that if todays date is between 1st December and 5th January, otherwise show the normal times. 尝试编写一个IF语句以显示圣诞节的开放时间,使用的公式是:今天的日期在12月1日至1月5日之间,否则显示正常时间。 But all I'm getting is the normal times. 但是我得到的只是平时。

$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>';
}

Don't use strings to do date math. 不要使用字符串进行日期数学运算。 Use DateTime() which is clearer and easier to understand. 使用更清晰易懂的DateTime()

DateTime() objects are comparable so you don't need to convert them to strings to do comparisons. DateTime()对象具有可比性,因此您无需将它们转换为字符串即可进行比较。 Additionally, it is timezone and daylight savings time aware (which doesn't come into play here but may at other times you works with dates). 此外,它还了解时区和夏令时(此处不起作用,但有时您可以使用日期)。

<?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>';
}

Additionally, I added the times to each day as DateTime, and strtottime() will use the current time and not the beginning or ending of each day so on the last day of the Xmas hours you will not show the right hours. 此外,我将时间添加为每天的DateTime, strtottime()将使用当前时间,而不是每天的开始或结束,因此在圣诞节时间的最后一天,您将不会显示正确的时间。 (You can also change the last day to be 1/6 00:00:00 ). (您也可以将最后一天更改为1/6 00:00:00 )。

Demo 演示版

strtotime doesn't understand your short time definition, try to use complete date in Ymd format ( 2017-12-01 and 2018-01-05 respectively). strtotime无法理解您的短时间定义,请尝试使用Ymd格式的完整日期(分别为2017-12-012018-01-05 )。 Please also notice that your comparison doesn't include edge dates so you may want to use <= and >= instead. 另请注意,您的比较不包括边缘日期,因此您可能要使用<=>=代替。

$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