What's the issue in a code written for comparing the date with today's date?

I’m comparing a date with current date(i.e. today’s date). It is expected that the error should come only when the date to be compared is greater than today’s date. It should not come for date which is less than or equal to today’s date.

I’ve written following code for it.

$submission_date = $_POST['submission_date']; //The date in mm-dd-yyyy format that is to be tested against today's date. The value in $submission date is 12-25-2014 
//This is a future date. Today's date is 12-10-2014 in dd-mm-yyyy format

$current_date = date('m-d-Y');

if (strtotime($submission_date) > strtotime($current_date))
{
   echo "Future date not accepted";
}

With the above code I’m not getting errors for future dates, sometimes I’m getting error for previous dates as well.

How to optimize and make this code correct and standard?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

If posted format is in m-d-Y, then you cannot convert it to unix timestamp directly with strtotime() function, because it will return false.

If you need to use strtotime() then change the input format to m/d/Y by simple str_replace().

On the other hand, you could use DateTime class, where you can directly compare objects:

$submission_date = DateTime::createFromFormat('!m-d-Y', $submission_date);
$today_date = new DateTime('today');

if ($submission_date > $today_date) {
    echo "submission_date is in the future\n";
}

demo

If you need to extract some information from DateTime objects, use format() method on them, which accepts same format as date() function:

echo $today_date->format('m/d/Y'); # 12/11/2014
echo $today_date->format('m-d-Y'); # 12-11-2014
echo $today_date->format('Y-m-d'); # 2014-12-11
echo $today_date->format('Y-Y-Y'); # 2014-2014-2014

demo

Solution 2

I think you need to compare date in ‘Y-m-d’ or ‘d-m-Y’ format. I think it is not possible to compare date in ‘m-d-Y’ format

Solution 3

As we have made changes in your code and we test it works from my side so can you try below.

$submission_date = $_POST['submission_date'];
$current_date = date('d-m-y H:i:s');
if (strtotime($submission_date) > strtotime($current_date))
{
   echo "Future date not accepted";
}

Hope this helps.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply