将天数转换为年和剩余天数


Convert days to years and days remaining

我正在尝试将天数转换为年数和剩余天数格式。这是我尝试过的:

<?php
$reg_date = date('Y-m-d', strtotime($whois_details[5])); // 1997-09-15
$total_days = (date('Y-m-d') - $reg_date) * 365; // 2014-07-30
$total_years = intval($total_days / 365);
$remaining_days = ($total_days % 365) % 30;
if ($total_days < 365) {
    $remaining_days = $total_days;
}
echo $total_years.' years and '.$remaining_days.' days';
?>

输出- 300

0 years and 300 days - THIS IS OK

输出- 500

1 years and 15 days - THIS IS NOT OK
http://codepad.org/MDQjsz5l

应该是500

1 years and 135 days

我搞错了什么?我检查了C尖锐的问题,并尝试转换它。

我不知道为什么你复制的代码是这样的,你能链接吗?

这当然忽略了日期的复杂性(如闰年),但作为该算法的典型工作方式的一个例子。为了解释闰年,您需要知道所讨论的时间跨度是否包括闰年。如果给你的只有几天的时间,这就是你能做的最好的了。

$days = 500;
$years_remaining = intval($days / 365); //divide by 365 and throw away the remainder
$days_remaining = $days % 365;          //divide by 365 and *return* the remainder

如果你想考虑闰年,你应该考虑在PHP中使用日期函数。

$date1 = new DateTime('2014-07-30');
$date2 = new DateTime('1997-09-15');
$interval = $date2->diff($date1);
echo $interval->format('%Y years, %m months, %d days');

或者对于你的问题

$years = $interval->format('%Y');// total years
$days = $interval->format('%a') - (int)$years*365;// total days - total years * days per year

但我相信以上两行可以用更日期函数的方式完成