How to get days and months number from a given day

2019-08-28 03:09发布

问题:

I'm going to write a function to print a number of days left between two dates. I would like it to tell the months and days left. For example:

45 days = 1month, 15 days
65 days = 2months, 5 days
10 days = 10 days

So I tried:

<?
$days=50;

if($days>"31"){
$time=$days/30;
}
echo $time;//1.67 month
?>

According to the code above. I expect the result to be like:

1 month, 20 days

Could you guys please suggest.

回答1:

Try:

$days = 50;

if ($days > 31){
    $month = floor($days/30); // return lowest whole integer
    $days = $days % 30; // calculate left days
}

echo $month . " => " . $days; // output `1 => 20`


回答2:

Get the month number for both months and subtract. Add in calculation for year change

Get day of months for both dates. If date2 > date1, subtract and you have the number of days, else remove 1 from month count and sumteact date



标签: php get days