Search code examples
phpdatediff

Issue with date_diff in PHP


I want to check expired date is before one month or not for that I have use below code

$expire_date = '2021-01-14 04:59:59';
date_default_timezone_set("Asia/Kolkata");

$date1 = new DateTime(date('Y-m-d H:i:s'));
$date2 = new DateTime($expire_date);
$interval = $date1->diff($date2);

echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ".PHP_EOL; die(); // difference 0 years, 10 months, 8 days

if($interval->m > 1 && $interval->y <= 0){
    $status = "Yes"; // for expired
}else{
    $status = "No"; // not expired
}

with this case it is showing me wrong data so how can I find expire date before one month from the current date in PHP


Solution

  • One way to do this is to generate a date which is one month from now, and compare the expiry date with that. If it is less, then the expiry is within one month:

    $now = new DateTime();
    $now->modify('+1 month');
    $date2 = new DateTime($expire_date);
    
    if ($date2 < $now) {
        echo "expiry is in less than 1 month\n";
    }
    else {
        echo "expiry is more than 1 month away\n";
    }