【问题标题】:Comparing dates and show the remainder left til expiry date in PHP比较日期并在 PHP 中显示剩余的到期日期
【发布时间】:2020-07-02 16:24:11
【问题描述】:

我正在尝试在 PHP 中创建一个订阅期为 14 天的应用程序。在我的数据库表中,我有开始日期和到期日期。显示“您的应用程序将在 --- 天后过期”的过期横幅让我有点困惑。

      $start = explode(' ', $billing->started_at); // to get the date only
      $end = explode(' ', $billing->expires_at);

      $date1=date_create($start[0]);
      $date2=date_create($end[0]);
      $diff=date_diff($date1,$date2);
      
      Session::put('days_left', $diff->format("%R%a days"));

请帮忙

【问题讨论】:

  • 您遇到了什么问题?计算差异、存储差异、显示差异还是其他方式?
  • 寻找差异
  • 你能告诉我们$billing->started_at$billing->expires_at的实际样子吗?另外,他们的数据库数据类型是什么?日期时间、时间戳等?
  • echo $billing->started_at; 2020-05-20 05:13:03。和 $billing->expires_at 2020-07-20 12:00:00 两个值 started_at 和 expires_at 都是时间戳@waterloomatt

标签: php date time


【解决方案1】:

理论上,您的代码应该可以工作,但您没有告诉我们实际问题是什么,所以这就是我的处理方法。

如果您只想使用时间戳的日期部分进行计算,则可以在创建 DateTime 对象之前对其进行格式化。

<?php

$start = new DateTime(date('Y-m-d', strtotime($billing->started_at)));  
$end = new DateTime(date('Y-m-d', strtotime($billing->expires_at)));

$difference = $start->diff($end);

echo $difference->format("Your application will expire in %a days.");

或者,您可以直接使用时间戳。取决于您要达到的目标。

<?php

$start = new DateTime($billing->started_at);  
$end = new DateTime($billing->expires_at);

$difference = $start->diff($end);

echo $difference->format("Your application will expire in %a days.");

工作示例: http://sandbox.onlinephpfunctions.com/code/417d4691483f53fe083735d257df4fb49b832c58

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多