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 Aug开发者_开发问答ust 12, 2011, 9:45 am
.
My dates are as follow:
- date 1
$created
- date 2
$updated
/ if no updated have been made value is0000-00-00 00:00:00
Any suggestion much appreciated.
$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.
Convert the date to timestamp:
if (strtotime($created) > strtotime($updated))
{
// ...
}
else
{
// ...
}
精彩评论