Squints
Squints

Reputation: 3

(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:

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.

Upvotes: 0

Views: 46

Answers (2)

Rwd
Rwd

Reputation: 35200

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!

Upvotes: 0

Sandeep
Sandeep

Reputation: 130

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.

Upvotes: 1

Related Questions