简体   繁体   中英

(PHP) Verifying if given date is between two other dates

I'm having an issue with some code that someone else has previously worked on.
The goal is to iterate through a directory and push any files that are within a certain date range to an array (files are in mmddyyy.txt format).
The (terribly named, not by my own doing) variables in the code represent the following:

  • $aYear - A given year, read in from a text file. This variable changes during every iteration of the loop. The same goes for $aMonth and $aDay.
  • $sYear1 - Start year. $sMonth1 and $sDay1 are used in respect to $sYear1.
  • $sYear2 - End year. $sMonth2 and $sDay2 are used in respect to $sYear2.
  • $isGood - File will be added to the array.

     $isGood = false; if($aYear >= $sYear1 && $aYear <= $sYear2) { if($aYear == $sYear1) { if($aMonth == $sMonth1) { if($aDay >= $sDay1 && $aDay <= $sDay2) { $isGood = true; } } else { if($aMonth >= $sMonth1 && $aMonth <= $sMonth2) { $isGood = true; } } } else if($aYear == $sYear2) { if($aMonth == $sMonth2) { if($aDay <= $sDay2) { $isGood = true; } } else { if($aMonth <= $sMonth2) { $isGood = true; } } } else { $isGood = true; } } if($isGood) { //echo "Found good article"; $a = $a . "===" . $file; array_push($result, $a); } 

I'm not getting the results that I expected. I'm looking for some help as to how I can simplify this code and get it working properly. I do need to keep this solution in PHP.

Thank you in advance.

It seems to me Month statement if($aMonth >= $sMonth1 && $aMonth <= $sMonth2) needs work eg start date- 03 Aug 2013 end date- 04 Sep 2016 and check date say 08 Nov 2013 would make isGood=false whereas it should be true.

Removing && $aDay <= $sDay2 and && $aMonth <= $sMonth2 should work.

As @Sandeep pointed out you're issues are with:

if ($aMonth >= $sMonth1 && $aMonth <= $sMonth2)

and

if ($aDay >= $sDay1 && $aDay <= $sDay2)

as you don't need to be comparing the date with end dates as well.

That being said you can clear up your code completely by doing something like:

$date = (new DateTime)->setDate($aYear, $aMonth, $aDay);
$start = (new DateTime)->setDate($sYear1, $sMonth1, $sDay1);
$end = (new DateTime)->setDate($sYear2, $sMonth2, $sDay2);

if ($start <= $date && $date <= $end) {
    //echo "Found good article";
    $a = $a . "===" . $file;
    array_push($result, $a);
}

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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