PHP将日期与今天的日期进行比较

时间:2017-05-05 13:44:53

标签: php date

我正在尝试以mm-yy的格式获取信用卡到期日期,看看该日期是否已过,所以我知道信用卡是否已过期。如果已过期,则会在expired

上插入一类<tr>

问题 我的代码导致样本日期为05/16被检查,并且脚本显示该卡未显示该显卡已有一年之久。

我的代码

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

先谢谢了,我已经尝试过搜索,但没有一个解决方案似乎适合我正在做的事情。

1 个答案:

答案 0 :(得分:7)

使用PHP的内置日期功能时,您需要确保使用valid datetime format。否则strtotime()将返回falseDateTime()将引发异常。

要使用非标准日期时间格式,您可以使用DateTime::createFromFormat()来解析日期时间字符串并返回DateTime()对象,您可以从中get a Unix Timestampconvert the date into another format或用它来比较其他DateTime个对象。

// 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');

因此,对于您的问题,您将执行以下操作:

$expires = \DateTime::createFromFormat('m/y', $card_history->expire);
$today   = new \DateTime();

if($expires < $today){$expired = 'expired';}

另见:

相关问题