Java LocalDate Class | parse() Method with Example

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

LocalDate Class parse() method

Syntax:

public static LocalDate parse(CharSequence c_seq);
public static LocalDate parse(CharSequence c_seq, DateTimeFormatter fmtr);
  • parse() method is available in java.time package.
  • parse(CharSequence c_seq) method is used to create an instance of LocalDate from parsing the given char sequence.
  • parse(CharSequence c_seq, DateTimeFormatter fmtr) method is used to create an instance of LocalDate from parsing the given char sequence based on the given formatter.
  • These methods may throw an exception at the time of the represent date.
    DateTimeParseException: This exception may throw when the given parameter can't parse.
  • These are static methods and it is accessible with the class name and if we try to access these methods with the class object then we will not get an error.

Parameter(s):

  • In the first cases, parse(CharSequence c_seq),
    • CharSequence c_seq – represents the sequence to parse in this object.
  • In the second cases, parse(CharSequence c_seq, DateTimeFormatter fmtr),
    • CharSequence c_seq – Similar as defined in the first case.
    • DateTimeFormatter fmtr – represents the formatter to format the sequence in this object.

Return value:

In both the cases, the return type of the method is LocalDate, it returns the date that holds the value parsed the given sequence in a formatted manner.

Example:

// Java program to demonstrate the example 
// of parse() method of LocalDate

import java.time.*;
import java.time.format.*;

public class ParseOfLocalDate {
    public static void main(String args[]) {
        CharSequence c_seq = "2005-06-05";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy");

        // Here, parse(CharSequence) create an
        // instance of LocalDate from a
        // CharSequence
        LocalDate l_da = LocalDate.parse(c_seq);

        // Display l_da
        System.out.println("LocalDate.parse(c_seq): " + l_da);

        // Here, parse(CharSequence,DateTimeFormatter)
        // creates an instance of LocalDate from a 
        // CharSequence by using the given
        // DateTimeFormatter
        l_da = LocalDate.parse("15-Aug-1991", dtf);

        // Display l_da
        System.out.println("LocalDate.parse(15-Aug-1991,dtf): " + l_da.toString());
    }
}

Output

LocalDate.parse(c_seq): 2005-06-05
LocalDate.parse(15-Aug-1991,dtf): 1991-08-15


Comments and Discussions!

Load comments ↻





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