Period parse() method in Java with Examples
The parse() method of Period Class is used to obtain a period from given string in the form of PnYnMnD where nY means n years, nM means n months and nD means n days.
Syntax:
public static Period parse(CharSequence text)
Parameters: This method accepts a single parameter text which is the String to be parsed.
Returns: This function returns the period which is the parsed representation of the String given as the parameter
Below is the implementation of Period.parse() method:
Example 1:
// Java code to demonstrate parse() method // to obtain period from given string import java.time.Period; class GFG { public static void main(String[] args) { // Get the String to be parsed String period = "P1Y2M21D"; // Parse the String into Period // using parse() method Period p = Period.parse(period); System.out.println(p.getYears() + " Years\n" + p.getMonths() + " Months\n" + p.getDays() + " Days"); } } |
1 Years 2 Months 21 Days
Example 2:
// Java code to demonstrate parse() method // to obtain period from given string import java.time.Period; class GFG { public static void main(String[] args) { // Get the String to be parsed String period = "-P1Y2M21D"; // Parse the String into Period // using parse() method Period p = Period.parse(period); System.out.println(p.getYears() + " Years\n" + p.getMonths() + " Months\n" + p.getDays() + " Days"); } } |
-1 Years -2 Months -21 Days
Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Period.html#parse-java.lang.CharSequence-
Recommended Posts:
- NumberFormat parse() method in Java with Examples
- Level parse() method in Java with Examples
- ZonedDateTime parse() method in Java with Examples
- SimpleDateFormat parse() Method in Java with Examples
- LocalDateTime parse() method in Java with Examples
- LocalTime parse() method in Java with Examples
- OffsetTime parse() method in Java with examples
- LocalDate parse() method in Java with Examples
- Instant parse() method in Java with Examples
- Period get() method in Java with Examples
- Period from() method in Java with Examples
- Period between() method in Java with Examples
- Period of() method in Java with Examples
- Period plus() method in Java with Examples
- YearMonth parse(CharSequence) method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

