'PHP Comparing a date to todays date

I am trying to take a credit card expiry date in the format of mm-yy and see if that date has passed so I know if the credit card has expired. If it has expired, a class of expired is inserted on the <tr>

My code results in a sample date of 05/16 being checked, and the script says that the card has not expired when obviously this card is a year old.

<?php foreach($card_historys as $card_history){ 
    $expired = "";
    $date = strtotime($card_history->expire); //Returns a date in mm/yy
    $noww = strtotime(date('m/y'));

    echo "expire: ".$date." / now: ".$noww."<br>";

    if($date < $noww){$expired = 'expired';}
  ?>
  <tr class="<?php echo $expired; ?>">

What did I do wrong?



Solution 1:[1]

When using PHP's built in date functionality, you need to make sure you are using a valid datetime format. Otherwise strtotime() will return false and DateTime() will throw an exception.

To work with non-standard datetime formats you can use DateTime::createFromFormat() to parse the datetime string and return a DateTime() object from which you can get a Unix Timestamp, convert the date into another format, or use it to compare to other DateTime objects.

// Date separated by dots
$date01 = \DateTime::createFromFormat('Y.m.d', '2017.04.18');

// Date with no separator
$date02 = \DateTime::createFromFormat('Ymd', '20170418');

// Get Unix timestamp
$timestamp = $date01->getTimestamp();

// Get MySQL format (ISO-8601)
$mysqlDate = $date02->format('Y-m-d');

So for your issue, you would do the following:

$expires = \DateTime::createFromFormat('m/y', $card_history->expire);
$today   = new \DateTime();

if($expires < $today){$expired = 'expired';}

See also:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community