[英](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). 目标是遍历目录并将特定日期范围内的所有文件推送到数组(文件为mmddyyy.txt格式)。
The (terribly named, not by my own doing) variables in the code represent the following: 代码中的(非常命名,不是我自己做的)变量表示以下内容:
$isGood - File will be added to the array. $ isGood-文件将被添加到阵列中。
$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.
我确实需要将此解决方案保留在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. 在我看来,月报表if($ aMonth> = $ sMonth1 && $ aMonth <= $ sMonth2)需要工作,例如开始日期-2013年8月3日结束日期-2016年9月4日,检查日期说2013年11月8日将使isGood = false,而应该是真的。
Removing && $aDay <= $sDay2 and && $aMonth <= $sMonth2 should work. 删除&& $ aDay <= $ sDay2和&& $ aMonth <= $ sMonth2应该可以。
As @Sandeep pointed out you're issues are with: 正如@Sandeep指出的那样,您遇到的问题是:
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! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.