How to check whether the date coming in $_POST array is not greater than today's date in PHP?

218 views Asked by At

The date to be checked is as follows :

$submission_date = 12-25-2014; //The date in mm-dd-yyyy format that is to be tested against today's date

Now I want to echo the error message since the date contained in a variable $submission_date is a future date.

How should I do this efficiently and effectively using PHP?

Thanks in advance.

3

There are 3 answers

16
RobP On

Many ways to do this (use DateTime::createFromFormat() to control exact format of input dates, for example) but perhaps the simplest that suits the example is:

$isFuture = (strtotime($submission_date) > strtotime($_POST['current_date']))

Note that OP changed the question. If desired date to test against is not in $_POST array, just replace strtotime($_POST['current_date']) with time() to use current system time.

To compare against current date, disregarding time of day, use:

$today = new DateTime(date("Y-m-d"));
// $today = new DateTime("today");  // better solution courtesy of Glavić
// see http://php.net/manual/en/datetime.formats.relative.php for more info
$today_timestamp = $today->getTimestamp();
8
fortune On

With PHP DateTime you can check whether the input date is future or old w.r.to the todate.

$submission_date = DateTime::createFromFormat('m-d-Y', $submission_date);
$submission_date = $submission_date->format('Y-m-d');
$current_date    = new DateTime('today');
$current_date    = $current_date->format('Y-m-d');

if ($submission_date > $current_date)
{
       echo "Future date";
}
else
{
       echo "Old date";
}
0
Glavić On

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