Search code examples
phpdatetimerelative-date

Turning a variable containing the number of months to X Years, X Months format?


This is a bit like the popular relative time (ago) except I'm not dealing with a timestamp but the number of months.

I'm not sure on how to go by this though?

Heres some examples to improve your understanding of my question:

If input was:

3

Output would be:

3 Months

If input was:

13

Output would be:

1 Year, 1 month

So for every 12 months its X Year(s) (if any) and then the remaining months are following it with X month(s).


Solution

  • You can use the mod operator to get remaining months:

    $years = (int)($total_months / 12);
    $months = $total_months % 12;