PHP Comparing a date to todays date

前端 未结 1 600
一向
一向 2021-01-29 14:40

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

相关标签:
1条回答
  • 2021-01-29 15:02

    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:

    • Convert one date format into another in PHP
    • Compare DateTime objects with comparison operators in PHP
    0 讨论(0)
提交回复
热议问题