【问题标题】:php - how to check if a date is in a given season (regardless of the current year)?php - 如何检查日期是否在给定季节(无论当年)?
【发布时间】:2014-02-05 12:41:51
【问题描述】:

旺季: 4 月 28 日 - 9 月 30 日, 12 月 27 日 - 1 月 3 日

淡季: 10 月 1 日 - 12 月 26 日, 1 月 4 日 - 4 月 27 日


我给了一个日期来检查:2014-02-18,我想在哪个季节包括它的情况下有 TRUE 或 FALSE。不分今年怎么办?

【问题讨论】:

标签: php date range


【解决方案1】:

尝试简单的日期比较:

function is_high_season($date) {
    $md = gmdate('m-d', strtotime($date));
    return 
        ('03-28' <= $md && $md <= '09-30') || 
        ('12-27' <= $md && $md <= '12-31') || 
        ('01-01' <= $md && $md <= '01-03');
}

demo

【讨论】:

  • @quardas:您为什么要使用具有 2 倍以上 if 语句的解决方案?此解决方案不适合您吗?
【解决方案2】:
$day = $d->format('j');
$month = $d->format('n');

if($month == 1 && $day <= 3) {
    return 'high';
} elseif $month < 4 || ($month == 4 && $day < 28)) {
    return 'low';
} elseif($month == 4 && $day >= 28) {
    return 'high';
} elseif($month < 10) {
    return 'high';
} elseif($month < 12 || ($month == 12 && $day < 27)) {
    return 'low';
} elseif($month == 12 && $day >= 27) {
    return 'high';
}

【讨论】:

  • 为什么会被降级?它完全符合 OP 的要求并且做得很好。有多个可能的答案这一事实并不会自动使其成为糟糕的答案。
【解决方案3】:
 $Date = date('Y-m-d');
    $Date=date('Y-m-d', strtotime($Date));;
    //echo $Date; // echos today! 
    $hiDateBegin = date('Y-m-d', strtotime("28/04/2014"));
    $hiDateEnd = date('Y-m-d', strtotime("30/09/2014"));
    $hiDateBegin2 = date('Y-m-d', strtotime("27/12/2014"));
    $hiDateEnd2 = date('Y-m-d', strtotime("03/01/2015"));

    $lowDateBegin = date('Y-m-d', strtotime("01/10/2014"));
    $lowDateEnd = date('Y-m-d', strtotime("26/12/2014"));
    $lowDateBegin2 = date('Y-m-d', strtotime("04/01/2015"));
    $lowDateEnd2 = date('Y-m-d', strtotime("27/04/2015"));

    if (($Date > $hiDateBegin) && ($Date < $hiDateEnd))
    {
      echo "is Hi Season";
    }
    if (($Date > $hiDateBegin2) && ($Date < $hiDateEnd2))
    {
      echo "is Hi Season";
    }
if (($Date > $lowDateBegin) && ($Date < $lowDateEnd))
    {
      echo "is Low Season";
    }
    if (($Date > $lowDateBegin2) && ($Date < $lowDateEnd2))
    {
      echo "is Low Season";
    }
    else
    {
    echo "Date doesn't fall in a season!";  
    }

【讨论】:

  • 为什么会被降级?它完全符合 OP 的要求并且做得很好。有多个可能的答案这一事实并不会自动使其成为糟糕的答案。
  • @Tularis: some1 here like to downvote without a comment ;( 我认为它被否决了,因为此代码在 2014 年以外的任何其他年份都不起作用?
猜你喜欢
  • 1970-01-01
  • 2015-01-23
  • 1970-01-01
  • 2013-07-15
  • 2013-10-31
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多