Close

Java Date Time - LocalDate.parse() Examples

Code Snippets Java Date Time Java Java API 


Class:

java.time.LocalDate

java.lang.Objectjava.lang.Objectjava.time.LocalDatejava.time.LocalDatejava.time.temporal.TemporalTemporaljava.time.temporal.TemporalAdjusterTemporalAdjusterjava.time.chrono.ChronoLocalDateChronoLocalDatejava.io.SerializableSerializableLogicBig

Methods:

public static LocalDate parse(CharSequence text)

Returns the local date instance according to provided text. The text must be valid per DateTimeFormatter.ISO_LOCAL_DATE.


public static LocalDate parse(CharSequence text,

DateTimeFormatter formatter)

Returns the local date instance according to provided text. The text must be valid per provided DateTimeFormatter instance.


Above methods will throw DateTimeParseException if the text is not valid according to the formatter being used.


Examples


package com.logicbig.example.localdate;

import java.time.LocalDate;

public class ParseExample {

public static void main (String... args) {
LocalDate d = LocalDate.parse("1987-06-25");
System.out.println(d);
}
}

Output

1987-06-25




package com.logicbig.example.localdate;

import java.time.LocalDate;

public class ParseExample2 {

public static void main (String... args) {
LocalDate d = LocalDate.parse("1987-6-25");
System.out.println(d);
}
}

Output

Caused by: java.time.format.DateTimeParseException: Text '1987-6-25' could not be parsed at index 5
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400)
at java.time.LocalDate.parse(LocalDate.java:385)
at com.logicbig.example.localdate.ParseExample2.main(ParseExample2.java:13)
... 6 more




package com.logicbig.example.localdate;

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

public class ParseExample3 {

public static void main (String... args) {
LocalDate d = LocalDate.parse("19870625",
DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(d);
}
}

Output

1987-06-25




package com.logicbig.example.localdate;

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

public class ParseExample5 {

public static void main (String... args) {
//first week of 2016 and 1st day of the first week.
LocalDate d = LocalDate.parse("2016-W01-1",
DateTimeFormatter.ISO_WEEK_DATE);
System.out.println(d);

//Second week of 2016 and 3rd day of the second week.
LocalDate d2 = LocalDate.parse("2016-W02-3",
DateTimeFormatter.ISO_WEEK_DATE);
System.out.println(d2);
}
}

Output

2016-01-04
2016-01-13

package com.logicbig.example.localdate;

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

public class ParseExample6 {

public static void main (String... args) {
LocalDate d = LocalDate.parse("2015_03_23",
DateTimeFormatter.ofPattern("yyyy_MM_dd"));
System.out.println(d);


}
}

Output

2015-03-23




See Also