繁体   English   中英

比较日期与不同季节的PHP

[英]comparing date with different seasons in php

您好,我使用php在变量中存储了从表单获取的日期,现在我想检查日期是否在季节中。我编写的代码如下:

$year = 2012;
$month1 = $_POST["month1"];
$date = $_POST["date"];
$result = "{$year}/{$month1}/{$date}";
echo $result;

现在

// finding first saturday in febraury
    $saturday = strtotime('First Saturday '.date('F o', mktime(0,0,0, $month, 1, $year)));
    echo "this is the first saturday in the given year:";
    echo date('Y/m/d', $saturday);

 // calculating first 12 weeks after the first saturday
    echo "<br/>";
    $season1 = strtotime ( '+12 week' , $saturday);
    echo "<br/>this is the first season:";
    echo date('Y/m/d', $season1);
    echo "<br/>";

 // calculating the one week gap after the first 12 weeks
    $season2 = strtotime ('+1 week' , $season1);
    echo "<br/>this is the first week break:";
    echo date('Y/m/d', $season2);
    echo "<br/>";

在这里,我需要做的是检查用户给定的日期是在season1还是season2 ..为此,我尝试

if ($result <= $season1)
    {
     echo "League yet to be opened";
    }
    else 
    {
    echo "league 1 is opened";
    }

但条件不是在这里检查,并且同样明智的做法是,我需要检查用户输入的8个季节的日期,我该怎么做..任何帮助都将不胜感激.....谢谢。

我建议您使用这样的代码和逻辑组织

从POST定义当前日期

不要忘记确保数据安全

年,月和日(天)必须为数字,此逻辑才能起作用。

$year = 2012;
$month1 = $_POST["month1"];
$date = $_POST["date"];

定义季节数组

$seasons = array(
   1 => array(
              'season_name' => 'first_season',
              'year_start' => 2012, 'year_end' => 2012, 
              'month_start' => 1, 'month_end' => 2, 
              'day_start' => 10, 'day_end' => 20
              ), 
   2 => array(
              'season_name' => 'second_season',
              'year_start' => 2012, 'year_end' => 2012, 
              'month_start' => 2, 'month_end' => 3, 
              'day_start' => 30, 'day_end' => 15
              ) 
 );

处理数据以定义季节

$season_match = array();
foreach($seasons as $season){
   if($year >= $season['year_start']) && if($year <= $season['year_end']){
       if($month >= $season['month_start']) && if($season<= $season['month_end']){
           if($date >= $season['date_start']) && if($season<= $season['date_end']){
               $seasons_match[] = $season['season_name'];
           }
       }
   }
}

测试错误并回显季节

if(count($season_match) == 0){
   echo 'Date is out of any season';
}
esleif(count($season_match) >1){
   echo 'ERROR: Date can be for more then one season at once';
}
else{
   echo $season_match; // This is the name of our season!
}

这是为您的任务提供简单明了解决方案的通用逻辑,但我尚未对其进行测试。

暂无
暂无

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

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