Method 1:If the date data is in the same format, use a simple comparison operator to compare dates.
Example :
// PHP program for comparing dates
// Declare two dates and
// initialize this
$date1
=
"1998- 11-24 "
;
$date2
=
"1997-03 -26 "
;
// Use the comparison operator for
// compare dates
if
(
$date1
>
$date2
)
echo
"$date1 is latest than $date2 "
;
else
echo
" $date1 is older than $date2 "
;
?>
Exit:1998-11 -24 is latest than 1997-03-26
Method 2:If both specified dates are in different formats, use function strtotime() to convert specified dates into appropriate format timestamps and finally compare these numerical timestamps to get the desired result.Example :
// PHP date comparison program
// Declare two dates in different
// format
$date1
=
" 12-03-26 "
;
$date2
=
"2011-10 -24 "
;
// Use the strtotime() function to convert
// date in dateTimestamp
$dateTimestamp1
=
strtotime
(
$date1
);
$dateTimestamp2
=
strtotime
(
$date2
);
// Compare stamp date
if
(
$dateTimestamp1
>
$dateTimestamp2
)
echo
"$date1 is latest than $date2"
;
else
echo
" $date1 is older than $date2 "
;
?>
Exit:12-03 -26 is latest than 2011-10-24
Method 3:Using the DateTime class to compare two dates.Example:
// PHP program for comparing dates
// Declare two dates in different
// format and use the DateTime() function
// convert date to DateTime
$date1
=
new
DateTime ( "12-11-24"
);
$date2
=
new
DateTime (
"2011-03-26"
);
// Compare dates
if
(
$date1
>
$date2
)
echo
$date1
-> format (
"Ymd"
).
"is latest than"
.
$date2
-> format (
"Ymd"
);
else
echo
$date1
-> format (
" Ymd "
).
"is older than"
.
$date2
-> format (
"Ymd"
);
?>
Exit:2012-11 -24 is latest than 2011-03-26