简体   繁体   中英

Comparing Date from PHP to MYSQL, strtotime not working

I have a DATE field on my MySQL table. Let's say the value is 2015-05-05. I would like to check if the current time is before or after that. This is my code:

foreach ($row as $row)
{
    $ExpDate = strtotime($row['exp_date']);
    $Today = strtotime(date("Y-m-d"));


    echo $Today . ' - ' . $ExpDate;
    if ($Today > $ExpDate)
    {
        exit('<M>LicenseExpired<M>');
    }
}

The problem is that it's not working. The value of exp without strtotime is 2015-05-05. It I add the strtotime, the value becomes an empty string.

How am I able to solve this problem or what would be a good way to compare dates in PHP?

When comparing dates in MySQL there is no reason to take the extra step and use string_to_time() . The below example should work just fine. The format of MySQL DATE is designed in such a way that comparisons of this nature work naturally without any extra steps needed.

foreach ($row as $row)
{
    $ExpDate = $row['exp_date'];
    $Today = date("Y-m-d");


    echo $Today . ' - ' . $ExpDate;
    if ($Today > $ExpDate)
    {
        exit('<M>LicenseExpired<M>');
    }
}

try this

foreach ($row as $row)
{   
$ExpDate = new DateTime($row['exp_date']);
$Today = new DateTime(date("Y-m-d"));
$interval = $ExpDate->diff($Today);
   //echo $interval->format('%R%a days');  <--- to diffenernce by days.

   if ($interval > 0)
{
    exit('<M>LicenseExpired<M>');
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM