您好我在互联网上搜索这个主题,似乎无法给我正确的输出? 我做错了什么?我想输出有效期的剩余天数,包括小时和分钟。
这就是我所做的,
$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分钟。哪个认为是错的?你能帮助我吗?谢谢!
答案 0 :(得分:0)
作为参考,%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
答案 1 :(得分:-1)
您的源代码工作正常,它可以满足您的期望。
是的,在那个日期错过了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");