PHP 将date_diff与时间流逝进行比较



如果我有

$time_interval = date_diff(date1, date2)

如何在 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'"

我试过了

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

但这会返回FALSE1 month and 20 days这显然是错误的

有没有类似的东西..?

$time_lapse = create_my_own_time_lapse(2months & 15 days)

那么比较两者会非常整洁

If ($time_interval >= $time_lapse)

溶液

date_diff重新调整DateInterval对象。我找到了创建自己的"2个月零15天"DateInterval的方法。这是我更新的代码:

访问 PHP 日期间隔手册了解详细信息

$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'";

你的代码几乎是正确的。只需删除and并添加strtotime()

从:

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

自:

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

最简单的方法是将您的时间转换为秒,然后将这些秒与等于 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'";

最新更新