How to parse a String in LocalDate

The java.time.LocalDate class can be parsed using the parse method or with a Formatter.

Syntax:


LocalDate parsed = LocalDate.parse("2017/10/13", DATE_FORMATTER);

Example:

The following example create a LocaDateTime using now. It then formats it in ISO_DATE_TIME, 24H format and 12H format. The output is then written in System out. Not that in 12h format a is added to the format to show if it is AM or PM.

Create the following java file:

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

public class LocalDateTest {

    public static void main(String[] argv) {
	LocalDate ld = LocalDate.now();

	// The formatter
	DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");

	// Parse the String
	LocalDate parsed = LocalDate.parse("2017/10/13", DATE_FORMATTER);

	System.out.println("Date in ISO format: " + parsed.format(DateTimeFormatter.ISO_DATE));

	String formattedDate2 = ld.format(DATE_FORMATTER);
	System.out.println("Date formatted back to String: " + formattedDate2);
    }
}


The output will be:

Date in ISO format: 2017-10-13
Date formatted back to String: 2017/10/13

References:

LocalDate Javadoc

Share this article:

Recent Comments