简体   繁体   English

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

[英]check a date between two dates - PHP

I want to check a certain date that is stored in my DB, if this date is during this fiscal year it prints valid if it is not it prints invalid 我想检查数据库中存储的某个日期,如果该日期在本会计年度内,则打印有效;如果不是,则打印无效

here is my php code: 这是我的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";}

but the problem is that i don't want to set the start and the end dates manually, is there a way to make it dynamic? 但是问题是我不想手动设置开始和结束日期,有没有办法使它动态? as it will be updated every year 因为它将每年更新

Try this, 尝试这个,

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

Here is working link 这是工作链接

This way your script will be a bit more dynamic . 这样,您的脚本将更加动态

// 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"
*/

check this on PHP Sandbox PHP Sandbox上检查一下

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

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