Comparing date with today date using strtotime
Discuss coding issues, and scripts related to PHP and MySQL.
-
Marius
- Posts:107
Comparing date with today date using strtotime
I've written following code to compare a date in a variable with today's date. If the date in a variable is greater than today's date the error message should be echoed. But it's not working properly in my case.
Code: Select all
$form_data['trans_date'] = '12-11-2014'; // Date to be compared with today's date in mm-dd-yyyy format
if(strtotime(date('m-d-Y')) < strtotime($form_data['trans_date'])) echo 'Error'; // if greater than today's date
else echo 'Success';
Actually today's date is 12-11-2014 (11th December 2014) and I'm indirectly comparing today's date with itself. So I should not get an error message since the date I'm comparing is not greater than today's date, but I'm getting the error message.
So how should I resolve this issue?
Admin
Posts:805
You may be meaning 11th Decemeber with 12-11-2014, but strtotime isn't seeing it that way.
If you need to use strtotime() then change the input format to m/d/Y (12/11/2014).
- On the other hand, you could use DateTime class, where you can directly compare objects:
Code: Select all
$submission_date = DateTime::createFromFormat('!m-d-Y', '12-11-2014'); // ! used to take the time 00:00:00 of that date
$today_date = new DateTime('today');
if($submission_date > $today_date) {
echo 'Error - submission_date is in the future';
}
else echo 'Success';