paul paul - 4 months ago 23
PHP Question

PHP DateTime credit card expiration

I'm trying to use DateTime to check if a credit card expiry date has expired but I'm a bit lost.

I only want to compare the mm/yy date.

Here is my code so far

$expmonth = $_POST['expMonth']; //e.g 08
$expyear = $_POST['expYear']; //e.g 15

$rawExpiry = $expmonth . $expyear;

$expiryDateTime = \DateTime::createFromFormat('my', $rawExpiry);
$expiryDate = $expiryDateTime->format('m y');

$currentDateTime = new \DateTime();
$currentDate = $currentDateTime->format('m y');

if ($expiryDate < $currentDate) {
echo 'Expired';
} else {
echo 'Valid';
}


I feel i'm almost there but the if statement is producing incorrect results. Any help would be appreciated.

Answer Source

It's simpler than you think. The format of the datess you are working with is not important as PHP does the comparison internally.

$expires = \DateTime::createFromFormat('my', $_POST['expMonth'].$_POST['expYear']);
$now     = new \DateTime();

if ($expires < $now) {
    // expired
}