1

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:

  • date 1 $created
  • date 2 $updated / if no updated have been made value is 0000-00-00 00:00:00

Any suggestion much appreciated.

Iladarsda
  • 10,640
  • 39
  • 106
  • 170
  • 2
    possible duplicate of: http://stackoverflow.com/questions/2113940/php-compare-date – JMax Aug 12 '11 at 10:00

2 Answers2

9
$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.

Iladarsda
  • 10,640
  • 39
  • 106
  • 170
J0HN
  • 26,063
  • 5
  • 54
  • 85
  • @JOHN - how to do it without knowing in front values of the dates? E.G there will be saved in the DB – Iladarsda Aug 12 '11 at 10:06
  • DateTime receive any valid date string. See http://www.php.net/manual/en/datetime.construct.php – J0HN Aug 12 '11 at 10:07
  • @John - Is there any walk around this? `$never_date` currently returning `November 30, -0001, 12:00 am`. – Iladarsda Aug 12 '11 at 10:10
  • 1
    @NewUser It depends on whether `0000-00-00 00:00:00` is greater or lesser than `$date1` as per your business logic. – Shoan Aug 12 '11 at 10:18
  • @John - if/else statement will be perfect for this situation. Thanks for your time and effort. – Iladarsda Aug 12 '11 at 10:23
1

Convert the date to timestamp:

if (strtotime($created) > strtotime($updated))
{
// ...
}
else
{
// ...
}
Pelshoff
  • 1,464
  • 10
  • 13