Duration parse(CharSequence) method in Java with Examples
The parse(CharSequence) method of Duration Class in java.time package is used to get a Duration from a string passed as the parameter. The format for the String to be parsed is “PnDTnHnMn.nS” where “nDT” means ‘n’ number of Days, “nH” means ‘n’ number of Hours, “nM” means ‘n’ number of Minutes and “nS” means ‘n’ number of Seconds. The formats accepted are based on the ISO-8601 duration format.
Syntax:
public static Duration parse(CharSequence text)
Parameters: This method accepts a parameter text which is CharSequence to be parsed into Duration.
Return Value: This method returns a Duration representing the time passed in the form of CharSequence as parameter.
Exception: This method throws DateTimeParseException if the text cannot be parsed to a duration.
Below examples illustrate the Duration.parse() method:
Example 1:
// Java code to illustrate parse() method import java.time.Duration; public class GFG { public static void main(String[] args) { // Get the text String time = "P2DT3H4M" ; // Duration using parse() method Duration duration = Duration.parse(time); System.out.println(duration.getSeconds()); } } |
183840
Example 2: To demonstrate DateTimeParseException
// Java code to illustrate parse() method import java.time.Duration; public class GFG { public static void main(String[] args) { // Get the text String time = "M" ; try { // Duration using parse() method Duration duration = Duration.parse(time); } catch (Exception e) { System.out.println( "Exception: " + e); } } } |
Exception: java.time.format.DateTimeParseException: Text cannot be parsed to a Duration
Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-
Recommended Posts:
- Duration minus(Duration) method in Java with Examples
- Duration compareTo(Duration) method in Java with Examples
- Duration dividedBy(Duration) method in Java with Examples
- Duration equals(Duration) method in Java with Examples
- Duration plus(Duration) method in Java with Examples
- Duration abs() method in Java with Examples
- Duration getNano() method in Java with Examples
- Duration isZero() method in Java with Examples
- Duration isNegative() method in Java with Examples
- Duration getSeconds() method in Java with Examples
- Duration toMillisPart() method in Java with Examples
- Duration from(TemporalUnit) method in Java with Examples
- Duration toNanosPart() method in Java with Examples
- Duration toSecondsPart() method in Java with Examples
- Duration toMinutesPart() 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.