toTotalMonths()
is an instance method of the Period
class used to return the total number of months in the Period
object. We multiply the number of years by 12
and add the number of months to calculate the number of months.
The
toTotalMonths()
method is only valid for those calendar systems with twelve months in a year.
The toTotalMonths()
method is defined in the Period
class. The Period
class is defined in the java.time
package. To import the Period
class, check the following import statement.
import java.time.Period;
public long toTotalMonths()
This method accepts no parameter.
This method returns the total number of months in the period.
In the below code, we calculate the total number of months in the Period
object and print the value to the console.
import java.time.Period;public class Main{public static void main(String[] args) {int numYears = 5;int numMonths = 10;int numDays = 13;Period period = Period.of(numYears, numMonths, numDays);System.out.printf("The total number of months in %s is %s.", period, period.toTotalMonths());}}