Given two dates (date1 and date2) and the task is to compare the given dates. Comparing two dates in PHP is simple when both the dates are in the same format but the problem arises when both dates are in a different format.
Method 1: If the given dates are in the same format then use a simple comparison operator to compare the dates.
Example:
<?php
$date1 = "1998-11-24" ;
$date2 = "1997-03-26" ;
if ( $date1 > $date2 )
echo "$date1 is latest than $date2" ;
else
echo "$date1 is older than $date2" ;
?>
|
Output:
1998-11-24 is latest than 1997-03-26
Method 2: If both of the given dates are in different formats then use strtotime() function to convert the given dates into the corresponding timestamp format and lastly compare these numerical timestamps to get the desired result.
Example:
<?php
$date1 = "12-03-26" ;
$date2 = "2011-10-24" ;
$dateTimestamp1 = strtotime ( $date1 );
$dateTimestamp2 = strtotime ( $date2 );
if ( $dateTimestamp1 > $dateTimestamp2 )
echo "$date1 is latest than $date2" ;
else
echo "$date1 is older than $date2" ;
?>
|
Output:
12-03-26 is latest than 2011-10-24
Method 3: Using DateTime class to compare two dates.
Example:
<?php
$date1 = new DateTime( "12-11-24" );
$date2 = new DateTime( "2011-03-26" );
if ( $date1 > $date2 )
echo $date1 ->format( "Y-m-d" ) . " is latest than "
. $date2 ->format( "Y-m-d" );
else
echo $date1 ->format( "Y-m-d" ) . " is older than "
. $date2 ->format( "Y-m-d" );
?>
|
Output:
2012-11-24 is latest than 2011-03-26
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.