How can I compare the date with today's date using UNIX timestamp values in PHP?

3k Views Asked by At

I've following variable containing date in MM-DD-YYYY format. I want to compare this date with today's date. If the date containing in a variable is greater than the today's date I want to echo "Error" and if it is less than or equal to today's date I want to echo "Success". For this thing I don't want to use DateTime class.

I think using UNIX Timestamp values could be a better option. If yo have any other better and efficient option you are welcome.

Following is the variable containing date in MM-D-YYYY format

$form_data['reg_date'] = '12-11-2014'; //This is today's date i.e. 11th December 2014

If the variable $form_data['reg_date'] contains date greater than today's date(i.e. 11th December 2014) it should give error message otherwise should echo success message.

Thanks.

3

There are 3 best solutions below

0
On BEST ANSWER

I've following variable containing date in MM-DD-YYYY format. I want to compare this date with today's date.

You cannot compare string representation of date in format m-d-Y. This format is invalid format, and php will not understand it. Read the manual what date formats are valid.

Best way to compare string dates is to have it in format Y-m-d or convert your string date to unix timestamp integer. But once you have date in Y-m-d format, it is trivial to convert it to unix timestamp, so converting it to timestamp just for comparing is an unnecessary step.

Convert m-d-Y to m/d/Y format, and then to unix timestamp:

$date = '12-25-2014';
$date = str_replace('-', '/', $date);
var_dump($date);
var_dump(strtotime($date));

if (strtotime($date) > strtotime('today')) echo "ERROR";
else echo "SUCCESS";

demo

But this I already explained in answer of your previous/same question (see 2nd link).

I think using UNIX Timestamp values could be a better option. If yo have any other better and efficient option you are welcome.

Other method could be converting format with sscanf() function:

$date = '12-25-2014';
sscanf($date, "%d-%d-%d", $m, $d, $Y);
$date = "$Y-$m-$d";
var_dump($date);

if ($date > date('Y-m-d')) echo "ERROR";
else echo "SUCCESS";

demo

But I would still recommend you to use DateTime class, like I already explained if my previous answer.

0
On

Please try below code

if(strtotime(date('d-m-Y')) == strtotime($form_data['reg_date'])){
        echo 'Today\'s Date';
}
0
On

First you have to convert your date in timestamp value like

$date_time = strtotime("11-12-2014");

and then you can do this to compare today date with the date you have.

$diff = $date_time - time();

This will gives you the date difference in seconds.