David Dalvin David Dalvin - 3 months ago 8
PHP Question

Comparing two dates in different month return nothing in PHP

I have a code that looks like this:

while ($DateNow <= $DateFinish) {
echo "<td>".$DateNow." | ".$DateFinish."</td>";
$DateNow = date("d-m-Y", strtotime("next day, ".$Datenow));
}


This code is inside a table so it will make a new cell for every day in a week.
$DateNow
start in this week monday,
$DateFinish
in Saturday. So it will make 6 new <td>.

It works well but the problem occur when the compared date is in different month, like for example Monday 29 Aug with Saturday 3 Sept, it returns nothing. I tried with every possible weeks that has 2 months in it, nothing show up. But when still in 1 month, it shows up.

Any thoughts about this?

Answer

When you order a set of dates in d-m-Y format lexicographically (alphabetically), you do not get the ordering you would expect.

For instance

30-01-2016
31-01-2016
01-02-2016
02-02-2016
28-02-2016
29-02-2016
01-03-2016
02-03-2016

becomes

01-02-2016
01-03-2016
02-02-2016
02-03-2016
28-02-2016
29-02-2016
30-01-2016
31-01-2016

after sorting.

To get a more sensible ordering when comparing in this way, you need to change the date format into something more conducive to natural ordering (such as Y-m-d).