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
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: