如何按指定的日期范围说出季节

时间:2013-07-18 05:01:01

标签: php arrays date range

我将按照给定的日期指定季节。我有4个季节,按日期(不是按月)。所以我决定使用in_arrayrange(),但它没有显示任何内容。

这是我的代码:

$p1=strtotime("2013-12-13");
$p2=strtotime("2014-02-20");
$h1a=strtotime("2014-02-21");
$h1b=strtotime("2014-04-31");
$l1=strtotime("2013-05-01");
$l2=strtotime("2013-10-31");
$h2a=strtotime("2013-11-01");
$h2b=strtotime("2013-12-19");


$today=strtotime(date("Y-m-d"));

if(in_array($today, range($p1, $p2))){
    echo "peak";
}elseif(in_array($today, range($h1a, $h1b))){
    echo "hi1";
}elseif(in_array($today, range($l1, $l2))){
    echo "low";
}else(in_array($today, range($h2a, $h2b))){
    echo "h2";
}

请你们改进我的代码。

此致

2 个答案:

答案 0 :(得分:1)

因为范围因内存限制而超出。我在范围http://codepad.viper-7.com/PLFObE中仅使用了2天,它显示了大部分输出。

您可以使用大于和小于来衡量日期。

if($today >= $p1 && $today <= $p2){
    echo "peak";
}elseif($today >= $h1a && $today <= $h1b){
    echo "hi1";
}elseif($today >= $l1 && $today <= $l2){
    echo "low";
}else($today >= $h2a && $today <= $h2b){
    echo "h2";
}

修改

Codepad

答案 1 :(得分:1)

我现在有了自己的解决方案。谢谢你们的试验。代码改编自:http://css-tricks.com/snippets/php/change-graphics-based-on-season/

<?
function current_season() {
       // Locate the icons
       $icons = array(
               "peak" => "peak season",
               "low" => "low season",
               "high1" => "high1 season",
               "high2" => "high2 season"
       );

       // What is today's date - number
       $day = date("z");

       //  Days of peak
       $peak_starts = date("z", strtotime("December 13"));
       $peak_ends   = date("z", strtotime("February 20"));

       //  Days of low
       $low_starts = date("z", strtotime("May 1"));
       $low_ends   = date("z", strtotime("October 31"));

       //  Days of high
       $high_starts = date("z", strtotime("February 21"));
       $high_ends   = date("z", strtotime("April 31"));

       //  If $day is between the days of peak, low, high, and winter
       if( $day >= $peak_starts && $day <= $peak_ends ) :
               $season = "peak";
       elseif( $day >= $low_starts && $day <= $low_ends ) :
               $season = "low";
       elseif( $day >= $high1_starts && $day <= $high1_ends ) :
               $season = "high";
       else :
               $season = "high2";
       endif;

       $image_path = $icons[$season];

       echo $image_path;
}
echo current_season();
?>