简体   繁体   中英

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>

The problem 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.

My code

<?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; ?>">

Thanks in advanced, I have tried searching around and none of the solutions seem to be appropriate for what I'm doing.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM