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?
If posted format is in
m-d-Y
, then you cannot convert it to unix timestamp directly withstrtotime()
function, because it will returnfalse
.If you need to use
strtotime()
then change the input format tom/d/Y
by simplestr_replace()
.On the other hand, you could use
DateTime
class, where you can directly compare objects:demo
If you need to extract some information from DateTime objects, use
format()
method on them, which accepts same format asdate()
function:demo