简体   繁体   中英

Checking a date between two dates bug, clueless

This function returns an array of dates in between two dates.

Now it works completely fine, except for some unknown reason, if I put it the month of November or the month of March as the arguments, I get an array of one day less. The other months work completely fine. I am absolutely clueless.

function getListofDatesInRange2($fromDate, $toDate)
{
    $fromDate = str_replace("-","/", $fromDate);
    $toDate = str_replace("-","/", $toDate);

    $dateMonthYearArr = array();
    $fromDateTS = strtotime($fromDate);
    $toDateTS = strtotime($toDate);

    for ($currentDateTS = $fromDateTS; $currentDateTS <= $toDateTS; $currentDateTS += (60 * 60 * 24)) {
        $currentDateStr = date("m-d-Y",$currentDateTS);
        $dateMonthYearArr[] = $currentDateStr;
    }

return $dateMonthYearArr;
}

I recoded it, and a while loop solved my issue. (although i have no idea what the issue was in the first place)

function getListofDatesInRange2($fromDate, $toDate)
{
$fromDate = str_replace("-","/", $fromDate);
$toDate = str_replace("-","/", $toDate);

$dateMonthYearArr = array();
$fromDateTS = strtotime($fromDate);
$toDateTS = strtotime($toDate);

array_push($dateMonthYearArr, date('m-d-Y', $fromDateTS));
while($fromDateTS < $toDateTS) {
    $fromDateTS += 86400;
    array_push($dateMonthYearArr, date('m-d-Y', $fromDateTS));
}
return $dateMonthYearArr;

}

Almost certainly this is caused by some dolt many years ago who decided that the day should go in between the month and the year, rather than some logical endianness (big-endian in most computing, little-endian in British English).

Instead, put your input dates in the format YYYY-mm-dd before putting them through strtotime . This will ensure that you always get the right dates out.

To test that this is indeed your problem, try:

$fromDateTS = strtotime($fromDate);
echo date("m-d-Y",$fromDateTS);

Make sure the date being shown is the same as the date you put in. Chances are, it isn't.

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