简体   繁体   English

如何检查过去是否超过2天而不是将来?

[英]How to check if it's more that 2 days in the past not the future?

I want to check if the date is more that or equals 2 days in the past only , But it also works if it's in the future. 我只想检查日期是否大于或等于过去2天,但是如果将来也可以使用。

Here is the code: 这是代码:

$d = new DateTime('04-06-2018');

$todayDate = new DateTime();

$interval = $d->diff($todayDate);

$days = $interval->format('%a');

if($days >= 2)
{echo 'true'; }
else
{echo 'false';}

It returns true whenever the difference between the two dates is more that or equals 2 , How to solve that? 每当两个日期之间的差大于或等于2时,它将返回true,如何解决呢?

You can do this by checking invert property in your DateInterval . 您可以通过检查DateInterval invert属性来执行此操作。

$d = new DateTime('3-04-2018');
$todayDate = new DateTime();
$interval = $d->diff($todayDate);

if($interval->format('%a') >= 2
    && 0 === $interval->invert
) {
    echo 'true';
} else {
    echo 'false';
}

扩展是否检查日期是否为过去:

if($days >= 2 && strtotime($d) < time())

There is one more way to acheive this 还有另一种方法可以实现这一目标

return $interval->format("%r%a"); 返回$ interval-> format(“%r%a”);

Cast to int if needed: 如果需要,则转换为int:

return (int)$interval->format("%r%a"); return(int)$ interval-> format(“%r%a”);

Here you will get positive and negative number to check future and past date. 在这里,您将获得正数和负数以检查将来和过去的日期。

Hope it helps 希望能帮助到你

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

相关问题 sfWidgetFormDate-未来仅40天,过去0天 - sfWidgetFormDate - only 40 days to future and 0 to the past 如何仅选择从今天开始计算的未来几天? - How to select only future days counting from today's date? PHP检查过去的日期是否为30天 - PHP check if date is 30 days in the past 如何计算从当前系统日期到过去和未来日期的365天,并使用php和mysql相应地获取数据 - How to count 365 days from current system date to past and future date and fetch the data accordingly using php and mysql 询问从当前日期到未来7天以及过去7天的数据 - ask data's from current date to 7 days ahead and past 7 days 如何设置条件以检查30天或30天以上的有效性 - How to put condition that will check the validity of 30 days or more than 30 days WooCommerce - 检查用户是否在过去 60 天内购买了产品 - WooCommerce - Check if user purchased a product in the past 60 days 如何将元素添加到过去的日子和以后的日子(仅工作日) - How to add an element to past days and upcoming days (weekdays only) 如何在 php 中使用天数计算今天的未来 - how to get future today to future calculate with days date in php 如何在 MYSQL 中获取过去 30 天的数据并使用 php 中的变量在循环内打印过去 30 天 - How to get data in past 30 days in MYSQL and Print Past 30 days inside a loop using a variable in php
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM