PHP将日期与今天的日期进行比较 [英] PHP Comparing a date to todays date

查看:248
本文介绍了PHP将日期与今天的日期进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

问题
我的代码导致检查示例日期为05/16,脚本说该卡显然没有过期。一岁。

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.

我的代码

<?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.

推荐答案

在使用PHP的内置日期功能时,您需要确保使用的是有效的日期时间格式。否则, strtotime()将返回 false DateTime()会引发异常。

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.

要使用非标准日期时间格式,可以使用 DateTime :: createFromFormat() 来解析日期时间字符串并返回 DateTime() 对象,您可以从中获取Unix时间戳将日期转换为另一种格式,或将其与其他 DateTime 对象进行比较。

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';}

另请参见:

  • Convert one date format into another in PHP
  • Compare DateTime objects with comparison operators in PHP

这篇关于PHP将日期与今天的日期进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆