[Java] Convert from ○ months to ○ years ○ months

less than 1 minute read


This is a method of calculating the number of years and the number of remaining months from the number of months. (Written in Java)

35 months is 2 years and 11 months

Feeling like this.

Conversion method

The code looks something like this.


public class YearMonth{
     public static void main(String args[]){
         int monthCount = 35;
         System.out.println(monthCount + "months" + monthCount/12 + "year" + monthCount%12 + "months");

The 35 months stored in the variable monthCount have been converted to years.

Years and months were calculated separately.

For the year, divide 35 months by 12 months (1 year) and round down the decimal point with Math.floor. And as it is, the decimal point is attached with .0, so put (int) in front and make it an integer.

Months can be calculated by taking the remainder from dividing 35 months to 12 months (1 year).