Java - How to parse String to convert to LocalDate

Using the LocalDate and DateTimeFormatter libraries, you can convert a character date to a Date object. Converting a string to a Date object is convenient for data processing such as date calculation.

Create a LocalDate object by parsing the date

You can use LocalDate.parse to parse a character and create a LocalDate object.

In the code below, DateTimeFormatter.ISO_DATE is declared as a constant "yyyy-mm-dd". This option allows parsing of strings of the form "yyyy-mm-dd".

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Example {
    public static void main(String args[]) {
        String string = "2019-01-10";
        LocalDate date = LocalDate.parse(string, DateTimeFormatter.ISO_DATE);
        System.out.println(date);
    }
}

Print

2019-01-10

Define Format to parse the date

If the date is not in the usual format like "Jan 10, 2019", you can create a pattern and use it to parse

The code below is an example of parsing characters by generating the pattern "MM month dd day of year yyyy". If you use the LocalDate.format API, the text is output in the form of a fommator.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Example {
    public static void main(String args[]) {
        String string = "2019년 01월 10일";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy년 MM월 dd일");
        LocalDate date = LocalDate.parse(string, formatter);
        System.out.println(date);
        System.out.println(date.format(formatter));
    }
}

Print

2019-01-10
2019년 01월 10일

You can use the following patterns in DateTimeFormatter.

pattern Example
yyyy-MM-dd “2019-07-04”
dd-MMM-yyyy “04-July-2019”
dd/MM/yyyy “04/07/2019”
yyyy-MM-dd'T'HH:mm:ssZ “2019-07-04T12:30:30+0530”
h:mm a “12:00 PM”
MM dd, yyyy "January 10, 2019"

Clean up

We learned how to convert text to LocalData object. For a general date, one defined as a constant can be used. If not, you can create a Formatter and parse it.

codechachaCopyright ©2019 codechacha