how to compare two dates in php code example
Example 1: php compare two dates
$today = date("Y-m-d");
$expire = $row->expireDate;
$today_time = strtotime($today);
$expire_time = strtotime($expire);
if ($expire_time < $today_time) { }
Example 2: php date compare with today
<?php
$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
if ($datetime1 > $datetime2) {
echo 'datetime1 greater than datetime2';
}
if ($datetime1 < $datetime2) {
echo 'datetime1 lesser than datetime2';
}
if ($datetime1 == $datetime2) {
echo 'datetime2 is equal than datetime1';
}
Example 3: php difference between two dates
$date1 = "2007-03-24";
$date2 = "2009-06-26";
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
printf("%d years, %d months, %d days\n", $years, $months, $days);
Example 4: date comparison function in php
Select if(Date('2020-10-01') > Date('2020-11-01'), '1', '2' ) as rslt_date
Example 5: php compare dates
$date1 = "2021-01-15";
$date2 = "2021-01-18";
if ($date1 < $date2) {
echo "$date1 is earlier than $date2";
} else {
echo "$date1 is later than $date2";
}