简体   繁体   English

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

[英]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. 我正在尝试以mm-yy的格式获取信用卡的到期日期,然后查看该日期是否已过,因此我知道信用卡是否已过期。 If it has expired, a class of expired is inserted on the <tr> 如果已过期,则在<tr>上插入一类expired

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. 问题我的代码导致检查了日期为05/16的示例日期,并且脚本显示该卡显然已过期,但该卡尚未过期。

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 . 使用PHP的内置日期功能时,需要确保使用有效的datetime格式 Otherwise strtotime() will return false and DateTime() will throw an exception. 否则, strtotime()将返回falseDateTime()将引发异常。

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. 要使用非标准日期时间格式,可以使用DateTime::createFromFormat()解析日期时间字符串,并返回一个DateTime()对象,从该对象可以获取Unix时间戳将日期转换为另一种格式 ,或者使用它进行比较到其他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');

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: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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