将天数转换为年,月,日格式

时间:2017-12-11 22:00:11

标签: php

我有这个问题。有人可以帮助我,如何将天数转换为XX年,XX月,XX天的格式...... 我创建了这个功能,

function convert($sum) {
    $years = ($sum / 365) ;
    $years = floor($years); 
    $month = ($sum % 365) / 30.5; 
    $month = floor($month); 
    $days = ($sum % 365) % 30.5; // the rest of days
    // Echo all information set
    echo 'DAYS RECEIVE : '.$sum.' days<br>';
    echo $years.' years - '.$month.' month - '.$days.' days';
}

convert(151);

151 天结果错误

  

DAYS RECEIVE:151天0年 - 4个月 - 1天

一定是4个月,28天不是1天......

http://sandbox.onlinephpfunctions.com/code/f5e6b4b4f6a27024b66ffbf04e80698722a3ecab

2 个答案:

答案 0 :(得分:3)

如果您使用更现代的PHP,以下内容基于每个月的实际天数:

$days = 151;

$start_date = new DateTime();
$end_date = (new $start_date)->add(new DateInterval("P{$days}D") );
$dd = date_diff($start_date,$end_date);
echo $dd->y." years ".$dd->m." months ".$dd->d." days";

请注意,它会有所不同,具体取决于当前日期,因此您可能希望将$start_date$end_date设置为从固定基线开始工作

$days = 151;

$start_date = new DateTime('1970-01-01');
$end_date = (new DateTime('1970-01-01'))->add(new DateInterval("P{$days}D") );
$dd = date_diff($start_date,$end_date);
echo $dd->y." years ".$dd->m." months ".$dd->d." days";

答案 1 :(得分:0)

这是您的问题的解决方案:

function convert($sum) {
    $years = floor($sum / 365);
    $months = floor(($sum - ($years * 365))/30.5);
    $days = ($sum - ($years * 365) - ($months * 30.5));
    echo “Days received: ” . $sum . “ days <br />”;
    echo $years . “ years, “ . $months . “months, “ . $days . “days”;
}