简体   繁体   English

PHP 比较 date_diff 到时间流逝

[英]PHP compare date_diff to lapse of time

If I have如果我有

$time_interval = date_diff(date1, date2)

How can I do this in PHP?如何在 PHP 中执行此操作?

If ($time_interval >= ('2 months and 15 days'))
    echo "time is '2 months and 15 days' or more"
else
    echo "time is less than '2 months and 15 days'"

I tried我试过了

if ($time_interval->m <= 2 and $time_interval->d < 15)

But this will return FALSE for 1 month and 20 days which is obviously wrong但这将返回FALSE 1 month and 20 days ,这显然是错误的

Is there something like..?有没有类似的东西..?

$time_lapse = create_my_own_time_lapse(2months & 15 days)

Then it would be very neat to compare both然后将两者进行比较会很整洁

If ($time_interval >= $time_lapse)

SOLUTION解决方案

date_diff retuns a DateInterval object. date_diff返回一个DateInterval object。 I found the way to create my own DateInterval for '2 months and 15 days'.我找到了为“2 个月零 15 天”创建自己的DateInterval的方法。 This is my updated code:这是我更新的代码:

Visit PHP DateInterval manual for details有关详细信息,请访问PHP DateInterval 手册

$today = new DateTime(date('Y-m-d'));
$another_day = new DateTime("2019-05-10");

$time_diff = date_diff($today, $another_day);

// 'P2M15D' is the interval_spec for '2 months and 15 days'
$time_interval = new DateInterval('P2M15D');

// Let's see our objects
print_r($time_diff);
print_r($timeInterval);

if($time_diff >= $time_interval)
    echo "<br/>time is '2 months and 15 days' or more";
else
    echo "<br/>time is less than '2 months and 15 days'";

your code is almost correct.你的代码几乎是正确的。 Just remove the and and add strtotime()只需删除and并添加strtotime()

from:从:

if ($time_interval >= ('2 months and 15 days'))
    echo "time is '2 months and 15 days' or more";
else
    echo "time is less than '2 months and 15 days'";

to:至:

if ($time_interval->getTimestamp()) >= strtotime('2 months 15 days'))
    echo "time is '2 months and 15 days' or more";
else
    echo "time is less than '2 months and 15 days'";

Easy way of doing this is converting your time to seconds and than compare these seconds with amount of seconds equal to 2 months and 15 days.这样做的简单方法是将您的时间转换为秒,然后将这些秒与等于 2 个月零 15 天的秒数进行比较。

$timeInterval = strtotime('2009-12-01') - strtotime('2009-10-01');
$overSeconds = 60 * 60 * 24 * 75; // 60 seconds * 60 minutes * 24 hours * 75 days

if($timeInterval >= $overSeconds)
    echo "time is '2 months and 15 days' or more";
else
    echo "time is less than '2 months and 15 days'";

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

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