Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

php - 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,

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

DAYS RECEIVE : 151 days
0 years - 4 month - 1 days

it must be 4 month ans 28 days not 1 day...

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you use more modern PHP, the following is based around actual days in each month:

$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

$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";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...