简体   繁体   English

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

[英]Convert Days to Year,Month,Day Format

I have this problem. 我有这个问题。 Can someone help me,how to convert number of days into the format XX Years, XX Month, XX Days... i created this function, 有人可以帮助我,如何将天数转换为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);

But with 151 days the result was wrong 但是在151天的结果是错误的

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

it must be 4 month ans 28 days not 1 day... 它必须是4个月和28天而不是1天......

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

If you use more modern PHP, the following is based around actual days in each month: 如果您使用更现代的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";

Note that it will vary, depending on the current date, so you might prefer to set $start_date and $end_date to work from a fixed baseline 请注意,它会根据当前日期而有所不同,因此您可能更愿意将$start_date$end_date设置$start_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";

This is the solution for your problem: 这是您的问题的解决方案:

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”;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM