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:
import java.time.Period;
class GFG {
public static void main(String[] args)
{
String period = "P1Y2M21D" ;
Period p = Period.parse(period);
System.out.println(p.getYears() + " Years\n"
+ p.getMonths() + " Months\n"
+ p.getDays() + " Days" );
}
}
|
Output:
1 Years
2 Months
21 Days
Example 2:
import java.time.Period;
class GFG {
public static void main(String[] args)
{
String period = "-P1Y2M21D" ;
Period p = Period.parse(period);
System.out.println(p.getYears() + " Years\n"
+ p.getMonths() + " Months\n"
+ p.getDays() + " Days" );
}
}
|
Output:
-1 Years
-2 Months
-21 Days
Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Period.html#parse-java.lang.CharSequence-
Last Updated :
28 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...