Wednesday, July 3, 2024
HomeLanguagesJavaPeriod toTotalMonths() method in Java with Examples

Period toTotalMonths() method in Java with Examples

The toTotalMonths() method of Period Class is used to obtain the total number of Months in the given period. It returns a long value depicting the same.

Syntax:

public long toTotalMonths()

Parameters: This method does not accepts any parameter.

Returns: This function returns the long value which is the total number of Months in the this Period.

Below is the implementation of Period.toTotalMonths() method:

Example 1:




// Java code to demonstrate toTotalMonths() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the String to be toTotalMonthsd
        String period = "P1Y2M21D";
  
        // Parse the String into Period
        Period p = Period.parse(period);
  
        System.out.println("Period: " + p);
  
        // Get the total number of months
        // using toTotalMonths() method
        System.out.println("Total number of Months"
                           + " in this Period: "
                           + p.toTotalMonths());
    }
}


Output:

Period: P1Y2M21D
Total number of Months in this Period: 14

Example 2:




// Java code to demonstrate toTotalMonths() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the String to be toTotalMonthsd
        String period = "-P1Y2M21D";
  
        // Parse the String into Period
        Period p = Period.parse(period);
  
        System.out.println("Period: " + p);
  
        // Get the total number of months
        // using toTotalMonths() method
        System.out.println("Total number of Months"
                           + " in this Period: "
                           + p.toTotalMonths());
    }
}


Output:

Period: P-1Y-2M-21D
Total number of Months in this Period: -14

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Period.html#toTotalMonths–

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments