【问题标题】:IF todays date is between 1st December and 5th January如果今天的日期在 12 月 1 日到 1 月 5 日之间
【发布时间】:2017-11-24 13:40:48
【问题描述】:

尝试编写一个 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>';
}

【问题讨论】:

  • 为了确定一个日期是否大于另一个,您需要一年。如果它们都在同一年,则一月永远不会大于十二月,并且只有一个月和一天,它们被假定为同一年。您的代码应该如何猜测您的意思是次年的一月?常识 - 如果我递给你两张纸,一张写着“1 月 5 日”,另一张写着“12 月 1 日”,并要求你按照哪一张在前排序,你的答案是什么?
  • Ken,我的回答是先给出哪个日期,将是第一次出现,第二次出现在下一年 - 这是常识。
  • @Lee Ken 可能不再在场,因此您可能需要删除您对他的评论并使用 @ 重新发布,就像我在这里为您所做的那样。记得遵循@member space message 格式。
  • @Lee 您没有尝试以下任何答案吗?我觉得两者都不错。

标签: php date


【解决方案1】:

不要使用字符串来计算日期。使用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)。

Demo

【讨论】:

  • 你不是说&lt;= $maxEnd吗?
【解决方案2】:

strtotime 不理解您的短时间定义,请尝试使用Y-m-d 格式的完整日期(分别为2017-12-012018-01-05)。另请注意,您的比较不包括边缘日期,因此您可能希望改用 &lt;=&gt;=

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 2015-05-14
    • 1970-01-01
    相关资源
    最近更新 更多