检查两个日期之间的日期 - PHP

时间:2017-03-05 10:46:13

标签: php date compare

我想检查存储在我的数据库中的某个日期,如果此日期是在本财政年度期间打印有效,如果不打印无效 < / p>

这是我的PHP代码:

$init_date= date("2016/07/01");
$end_date= date("2017/06/30");
$i_date = strtotime($init_date);
$e_date = strtotime($end_date);
$date_db= strtotime($date);// this $date is retrieved from my DB
if ($e_date > $date_db && $i_date < $date_db) 
     { echo "valid";}
else { echo "invalid";}

但问题是我不想手动设置开始和结束日期,有没有办法让它动态化?因为它将每年更新

2 个答案:

答案 0 :(得分:1)

试试这个,

<?php
$start_date = date('Y-m-d', strtotime(str_replace("/", "-", $initdate)));
$end_date   = date('Y-m-d', strtotime(str_replace("/", "-", $end_date)));
$new_date   = date('Y-m-d', strtotime(str_replace("/", "-", $date)));
 if (($start_date < $new_date && $new_date < $end_date) || ($end_date < $new_date && $new_date < $start_date)) {
    echo "valid";
} else {
    echo 'invalid';
}

这是有效的link

答案 1 :(得分:0)

通过这种方式,您的脚本会更加 动态

// the below snippet checks the date retrieved from database
// against fiscal periods between years 2000 and 2050 and return the 
// valid dates
$endYear=2000;
while($endYear<=2050) {
$end = $endYear.'/06/30';
$endDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = $initDate->sub(new DateInterval('P1Y'))->add(new DateInterval('P1D'));
$ddb = '2016-09-27';
$dateFrodDB = DateTime::createFromFormat('Y-m-d', $ddb);
if ($dateFrodDB>=$initDate && $dateFrodDB<=$endDate) 
     { echo "valid\n";
         echo "\tStartDate->\"".$initDate->format("Y-m-d")."\"\n";
         echo "\tEndDate->\"".$endDate->format("Y-m-d")."\"\n";
         echo "\tDateFromDatabase->\"".$dateFrodDB->format("Y-m-d")."\"\n";
     }
$endYear++;
}

/* output
   valid
        StartDate->"2016-07-01"
        EndDate->"2017-06-30"
        DateFromDatabase->"2016-09-27"
*/

PHP Sandbox

上查看