Iladarsda
Iladarsda

Reputation: 10696

How to compare two dates in php and echo newer one?

How to compare two dates in php and echo newer one?

My dates are in the following format: date("F j, Y, g:i a"); which give us August 12, 2011, 9:45 am.

My dates are as follow:

Any suggestion much appreciated.

Upvotes: 1

Views: 1378

Answers (2)

J0HN
J0HN

Reputation: 26941

$date1 = new DateTime("August 12, 2011, 9:45 am");
$date2 = new DateTime("August 12, 2011, 10:45 am");

$never_date = ($date1<$date2)?$date1:$date2;

echo $never_date->format("F j, Y, g:i a");

But note, that 0000-00-00 00:00:00 is a valid input for DateTime(), but will not work as expected. It will result in a -0001-11-30 00:00:00 (at least for PHP 5.3-VC9-nts on Win7 x64).

Update: I see two options for workarouning that 0000-00-00 00:00:00

  • Allow nulls in that column in your DB and remove DEFAULT 0000-00-00 00:00:00.
  • Check if $updated == '0000-00-00 00:00:00' and if so, just return $created:
  • Check if $updated == '' (empty string) and if so return $created:

    if ($updated=='0000-00-00 00:00:00' || $updated=='')
        $never_date = $created;
    else
        $never_date = ($created<$updated)?$created:$updated;
    

I doubt that it's right behaviour to show 0000-00-00 00:00:00 for a record that was never updated.

Upvotes: 9

Pelshoff
Pelshoff

Reputation: 1464

Convert the date to timestamp:

if (strtotime($created) > strtotime($updated))
{
// ...
}
else
{
// ...
}

Upvotes: 1

Related Questions