【问题标题】:How to correctly calculate time remaining from php date time如何正确计算 php 日期时间的剩余时间
【发布时间】:2020-10-11 17:08:40
【问题描述】:

到期日期为 unix 时间戳,大约 2020 年 9 月 30 日上午 6 点

$expiry_date_time = 160142766; //30 sept 2020 6AM
$dt1 = new DateTime();
$dt1->setTimestamp($expiry_date_time);
$now = new DateTime();
$i = $now->diff($dt1);
$time_remaining = $i->format('%y years %m months %a days %h hours %i minutes');
echo $time_remaining;

今天运行代码时的输出(2020 年 10 月 11 日)

0 years 0 months 11 days 7 hours 19 minutes

此代码不会给出不正确的结果,但它无法区分过期和未过期,就像在上述情况下订阅已过期它给出的输出 11 天,这并不完全不正确,因为它已经过期了 11 天如果你计算但不应该是负 11 天? 如果我将到期日期设为未来两天,它将正确计算并输出 2 天 xx 小时和 xx 分钟。 如何区分过期和未过期?

【问题讨论】:

  • 可以比较expired DateTimecurrent DateTime是否过期

标签: php


【解决方案1】:

DateInterval 有一个 invert 标志用于此目的:

invert

如果区间表示负时间段,则为 1,否则为 0。

$expiry_date_time = 160142766; //30 sept 2020 6AM
$dt1 = new DateTime();
$dt1->setTimestamp($expiry_date_time);
$now = new DateTime();

// What you're doing right now
$i = $now->diff($dt1);
var_dump($i->invert);  // int(1)

// If you're doing it the other way around
$i = $dt1->diff($now);
var_dump($i->invert);  // int(0)

Demo

【讨论】:

    【解决方案2】:
    $expiry_date_time = 160142766; //30 sept 2020 6AM
    $dt1 = new DateTime();
    $dt1->setTimestamp($expiry_date_time);
    $now = new DateTime();
    $i = $now->diff($dt1);
    $time_remaining = $i->format('%y years %m months %a days %h hours %i minutes');
    if($expiry_date_time - $now()->getTimestamp() < 0) {
        $time_remaining = "expired $time_remaining ago";
    }
    echo $time_remaining;
    

    如果它是过去的,这将在文本中添加一些文本,以确保您知道它是否已过期。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 2018-02-28
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多