【问题标题】:PHP Subtract Date with hours and minutesPHP用小时和分钟减去日期
【发布时间】:2014-08-13 09:30:08
【问题描述】:

您好,我已经在互联网上搜索了有关此主题的信息,但似乎无法给我正确的输出? 我做错了什么?我想用小时和分钟输出过期时间的剩余天数。

这就是我所做的,

$date_expire = '2014-09-12 23:59:59';  
$date = new DateTime($date_expire);
$now =  new DateTime();
echo $date->diff($now)->format("%d days, %H hours and %i minutes");

我来自菲律宾,我写这篇文章的当前日期和时间是 2014 年 8 月 13 日下午 5:26 输出给了我 29 天 12 小时 30 分钟。哪个是错误的?你能帮助我吗?谢谢!

【问题讨论】:

  • 服务器可能有其他时区。将其设置在您的 php.inidate_defualt_timezone_set
  • 使用%a 代替%d,这将返回天差总数。

标签: php time subtraction


【解决方案1】:

作为参考,%a 是要走的路。这里结合一个简单的检查某些订阅是否已过期。

date_default_timezone_set('Asia/Manila');

// August 13, 2014 5:26pm
$date_now    = '2014-08-13 17:26:00';
$date_expire = '2014-09-12 23:59:59';

$now     = new DateTime($date_now);
$expires = new DateTime($date_expire);

$diff = $expires->diff($now)->format("%a days, %h hours and %i minutes");

if ($now < $expires) {
    echo "Your subscription will expire in $diff", PHP_EOL;
} else {
    echo "Your subscription expired $diff ago", PHP_EOL;
}

输出:

Your subscription will expire in 30 days, 6 hours and 33 minutes

今天运行它,$now = new DateTime(); 给出了这个输出:

Your subscription expired 168 days, 2 hours and 56 minutes ago

【讨论】:

    【解决方案2】:

    您的源代码运行良好,并且符合您的预期。

    是的,那天错过了 29 天 12 小时 30 分钟和几个月。

    问题是您没有打印出月份(:

    这里有包含月份的脚本:

    // this is your start date
    $date_expire = "2014-09-12 23:59:59";
    // build a DateTime instance from it
    $date = new DateTime($date_expire);
    // another instance for the date of NOW
    $now =  new DateTime();
    // print the difference with %m (months) included
    echo $date->diff($now)->format("%m months, %d days, %H hours and %i minutes");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-26
      • 2018-03-06
      • 2017-08-03
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      相关资源
      最近更新 更多