Period toTotalMonths() method in Java



The total number of months for a particular Period can be obtained using the toTotalMonths() method in the Period class in Java. This method requires no parameters and it returns the total number of months in the Period in the form of a long value.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.time.Period;
public class Demo {
   public static void main(String[] args) {
      String period = "P2Y1M15D";
      Period p = Period.parse(period);
      System.out.println("The Period is: " + p);
      System.out.println("The total number of months are: " + p.toTotalMonths());
   }
}

Output

The Period is: P2Y1M15D
The total number of months are: 25

Now let us understand the above program.

First, the Period is displayed. Then the total number of months for the Period are obtained using the toTotalMonths() method and displayed. A code snippet that demonstrates this is as follows:

String period = "P2Y1M15D";
Period p = Period.parse(period);
System.out.println("The Period is: " + p);
System.out.println("The total number of months are: " + p.toTotalMonths());
Updated on: 2019-07-30T22:30:25+05:30

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements