Ginxx0009 Ginxx0009 - 6 months ago 12
PHP Question

Check if today's date is passed the expiration date

Can someone out there help me with this:

<?php
include 'include/db_config.php';

$result = $dbs->prepare("SELECT * FROM service_info WHERE id = :id");
$result->bindParam(':id', $_SESSION['id']);
$result->execute();
for ($i=0;$i = 0; $row = $result->fetch(); $i++) {
?>

<td><?php echo $row['datepicker']; ?></td>

<?php



$offset = strtotime("+1 day");
$enddate = date("Y-m-d H:i:s", $offset);
echo $enddate . "</br>";
if ($enddate < $startdate) {
echo "expired";
} else {
echo "active";
}
}
?>


What I want to achieve is to find out if the date value held in
$row['datepicker']
was more than 2 days ago. If it was more than 2 days ago I want it to echo
expired
and otherwise I want it to show
active
.

For example:
$row['datepicker']
could contain the date: May 18, 2016 (based on the users input - not a fixed value). That would mean it's expiration date would be: May 20,2016. If today's date is greater than or equal to May 20th 2016, it should echo
expired
. If today's date was May 19th 2016 it should echo
active
because it is not yet two days in the past.

Answer

Based on your comments, you want to take the $startdate and add two days to it. If today's date is passed that time then you want to print expired and otherwise print active.

$startdate = "16-May-2016";
$expire = strtotime($startdate. ' + 2 days');
$today = strtotime("today midnight");

if($today >= $expire){
    echo "expired";
} else {
    echo "active";
}

In this case it will echo expired because, at the time of writing this, we are two days passed the 16th May. If you changed the $startdate to be 17th May it would echo active because that is only 1 day in the past.

For your specific problem you would want to change $startdate to look like this:

$startdate = $row['datepicker'];

Whenever the date specified in $startdate is greater than or equal to 2 days in the past it will show expired otherwise it will show active.


What are we doing here?

It's quite simple. We take advantage of strtotime() to get the timestamp of the day it will be +2 days from your $startdate value. Then we get today's date at midnight (so the actual timestamp would be the equivalent of 18-May-2016 00:00:00).

Our last step is to compare the two timestamps and see if today's date is greater than or equal to the expiry date.


Note: This assumes that your $startdate is in a format that is compatible with strtotime().