Comparing two dates in different month return nothing in PHP

5

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?

514

Answer

Solution:

When you order a set of dates ind-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 asY-m-d).

People are also looking for solutions to the problem: Can't find the images uploaded by php script

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.