Question

I have a number of months (say 38 months).

I need to know how to convert this 38 value to say, 3 years and 2 months.

This is what I have so far:

$months = 38;
$years = $months / 12;

$years is equal to 3.1666666666667. I am wondering how to be left with simply 3 years, and then the 2 months left over?

Was it helpful?

Solution

You could calculate the time with the mod operator

$months = 38;
$years = floor($months / 12);
$resMonths = $months % 12;

OTHER TIPS

You can do this.

$months = 38;
$years = floor($months / 12);

//Use modulo to get the remainder
$months = $months % 12;

echo $years . " years and " . $months . " months";

The following code will output “3 years and 2 months”:

$months = 38;
print(floor($months/12)." years and ".($months%12)." months");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top