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

Introduction

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:

Demo

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   www.ja  va 2s  . c o  m*/
  }
}

Result

Related Topic