-3

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Hunter
  • 414
  • 5
  • 15
  • 1
    we cannot reproduce when we do not know contents of your variables; so user `var_export`. Also show code that actually is running; this has syntax errors. – vv01f May 05 '17 at 13:49
  • Which variables are you unsure sure about? The only variable not set in the snippet is $card_history->expire which I have mentioned is mm/yy – Hunter May 05 '17 at 13:52
  • http://stackoverflow.com/questions/2167916/convert-one-date-format-into-another-in-php?noredirect=1&lq=1 Check this – Lakindu Gunasekara May 05 '17 at 13:55

1 Answers1

7

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:

Community
  • 1
  • 1
John Conde
  • 217,595
  • 99
  • 455
  • 496