Java Duration Class | parse() Method with Example

Duration Class parse() method: Here, we are going to learn about the parse() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 16, 2020

Duration Class parse() method

  • parse() method is available in java.time package.
  • parse() method is used to return a Duration that parses the given char sequence and char sequence follow some ISO -8601 standard format like PnDTnHnMn.nS.
  • parse() method is a static method, it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
  • parse() method may throw an exception at the time of parsing the given sequence.
    DateTimeParseException: This exception may throw when the given parameter couldn't parse.

Syntax:

    public static Duration parse(CharSequence cs);

Parameter(s):

  • CharSequence cs – represents the char sequence to parse to a Duration.

Return value:

The return type of this method is Duration, it returns the Duration that holds the parse value of the given sequence to a Duration.

Example:

// Java program to demonstrate the example 
// of parse(CharSequence cs) method of Duration

import java.time.*;

public class ParseOfDuration {
    public static void main(String args[]) {
        // parses the given sequence in this Duration du1 
        // i.e. 1D:1H:20M:10S in a standard format PnDTnHnMn.S
        Duration du1 = Duration.parse("P1DT1H20M10S");

        // Display du1
        System.out.println("Duration.parse(P1DT1H20M10S): " + du1);

        // parsees the given sequence in this Duration du1 
        // i.e. 1D:1H: in a standard format PnDTnHnMn.S
        Duration du2 = Duration.parse("P1DT1H");

        // Display du2
        System.out.println("Duration.parse(P1DT1H): " + du2);
    }
}

Output

Duration.parse(P1DT1H20M10S): PT25H20M10S
Duration.parse(P1DT1H): PT25H


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.