Java - Parse a string in MM/dd/yyyy format using a DateTimeFormatter to create a LocalDate


DateTimeFormatter class does not know the type of datetime object parsed from the strings.

Most of methods return a TemporalAccessor object that you can query to get the datetime components.

You can pass the TemporalAccessor object to the from() method of the datetime class to get the specific datetime object.

The following code shows how to parse a string in MM/dd/yyyy format using a DateTimeFormatter object to construct a LocalDate:


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

public class Main {
  public static void main(String[] args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    TemporalAccessor ta = formatter.parse("01/10/2018");
    LocalDate ld = LocalDate.from(ta);
    System.out.println(ld);/*from w  ww .ja  v a 2 s  .co m*/


Related Topic