Java 8 – Convert String to LocalDate, LocalDateTime in Java

The Java 8 LocalDate-Time API includes a parse() method, which can be used to parse a given input string using a specified format.

Convert String to LocalDate in java
 

Parse a String to form a Date Object

By default, the parse() method will format based on the default DateTimeFormatter.
For example, to parse the string “2016-08-23”, the default LocalDate.parse() method can be called.

  LocalDate newDate = LocalDate.parse("2016-08-23");
  System.out.println("Parsed date : " + newDate);

Output:


Parsed date : 2016-08-23

 
Similarly, the default LocalDateTime.parse() method can be used to parse a String to a DateTime object.

Parse a String to form a Date-Time Object

  LocalDateTime newDatetime = LocalDateTime.parse("2016-08-23T12:23:45");
  System.out.println("Parsed datetime : " + newDatetime);

Output:


Parsed datetime : 2016-08-23T12:23:45

 

Parse a String to a LocalDate or LocalDateTime object using a DateTimeFormatter

A different DateTimeFormatter can be specified as a second argument to the parse() method.
Refer this link for the Predefined Formatters.
 
http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
 

Example 1

  LocalDate newDate = LocalDate.parse("2016-08-23",DateTimeFormatter.ISO_DATE);
  System.out.println("Parsed date : " + newDate);
    
  LocalDateTime newDatetime = LocalDateTime.parse("2016-08-23T12:23:45",DateTimeFormatter.ISO_DATE_TIME);
  System.out.println("Parsed datetime : " + newDatetime);

Output:


Parsed date : 2016-08-23
Parsed datetime : 2016-08-23T12:23:45

 

Parse a String to a LocalDate or LocalDateTime object using Custom Parser

For custom patterns, we can Formatter using the ofPattern(String) and ofPattern(String, Locale) methods as shown in examples below :

Example : Parsing String of pattern yyyy MM dd to LocalDate

        LocalDate newDate = LocalDate.parse("2016 11 23",DateTimeFormatter.ofPattern("yyyy MM dd"));
  System.out.println("Parsed date : " + newDate);

Output:


Parsed date : 2016-11-23

 

Example : Parsing String of pattern dd/MM/yyyy to LocalDate

        LocalDate newDate = LocalDate.parse("23/11/2016",DateTimeFormatter.ofPattern("dd/MM/yyyy"));
  System.out.println("Parsed date : " + newDate);

Output:


Parsed date : 2016-11-23

 

Example : Parsing String of pattern dd Mon yyyy to LocalDate

  LocalDate newDate = LocalDate.parse("23 Aug 2016",DateTimeFormatter.ofPattern("d MMM uuuu"));
  System.out.println("Parsed date : " + newDate);

Output:


Parsed date : 2016-08-23

 

© 2016 – 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

2 comments

  1. Anurag Singh

    This java 8 example is really nice and very useful.
    thanks for sharing this kind of articles.

  2. nice work keep it up.

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: