How to parse String to LocalDate in Java 8? DateTimeFormatter Example

From Java 8 onward, you are no longer dependent on the buggy and bulky SimpleDateFormat class to parse and format date Strings into real Date object in Java e.g. java.util.Date. You can use the DateTimeFormatter class from java.time package for all your formatting and parsing need. You are also no longer required to use another buggy class java.util.Date if you are doing fresh development, but if you have to support legacy code then you can also easily convert LocalDate and LocalTime to java.util.Date or java.sql.Date. In this tutorial, we will learn about both parsing String to date in Java and formatting Date into String. Remember, parsing is equivalent to converting String to date and formatting means converting a Date to String in Java.

Another key aspect of parsing and formatting is the format e.g. ddMMyyyy is a date format. If your date String is something like "10092015" then you need to use "ddMMyyyy" while parsing. Same is true while formatting Date to String. Java is very flexible in terms of date formats and allows you to construct a variety of formats including popular EU and US style.

There are also some pre-defined formatting available in Java 8 e.g. ISO_FORMAT for dd-MM-yyyy. By the way, actual parsing and formatting are done by respective classes e.g. LocalDate, LocalTime, and LocalDateTime. So, if your date String contains both date and time part then use LocalDateTime class, instead of using LocalDate or LocalTime.

Java 8 examples of parsing String to LocalDate

Here is our complete Java program to demonstrate how to parse a formatted String to LocalDate in Java. Remember, LocalDate is a new class from java.time package which represents the date without the time. In this program, I have shown you how to convert String to different date formats e.g. yyyyMMdd, yyyy-MM-dd, dd/MM/yy etc into LocalDate in Java 8.  You can further read Java SE 8 for Really Impatient By Cay S. Horstmann to learn more about new Date and Time API in Java 8.

Java Program to parse String to Date in Java 8
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Locale;

 * Java Program to demonstrate how to use DateTimeFormatter class
 * to parse String to date in Java 8 and format date to String in
 * various formats e.g. dd-MM-yyyy
 * @author WINDOWS 8
public class Java8Demo {

    public static void main(String args[]) {

        // BASIC_ISO_DATE formatter can parse date in yyyyMMdd format
        DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
        LocalDate date = LocalDate.parse("20150927", formatter);
        System.out.println("date string : 20150927, " + "localdate : " + date);
        // The ISO date formatter format or parse date in yyyy-MM-dd format
        // such as '2015-09-27' or '2015-09-27+01:00'
        // This is also the default format of LocalDate, if you print LocalDate
        // it prints date in this format only.
        formatter = DateTimeFormatter.ISO_DATE;
        date = LocalDate.parse("2015-09-27", formatter);
        System.out.println("date string : 2015-09-27, " + "localdate : " + date);
        // dd/MM/yyyy is also known as British or French date format, popular
        // in England, India and France.
        formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        date = LocalDate.parse("27/09/2015", formatter);
        System.out.println("date string : 27/09/2015, " + "localdate : " + date);
        // MM/dd/yyyy is also known USA standard date format
        formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
        date = LocalDate.parse("09/27/2015", formatter);
        System.out.println("date string : 09/27/2015, " + "localdate : " + date);
        // parsing date in dd-MMM-yy format e.g. 27-SEP-2015
        // Make sure you set the default Local to Locale.US otherwise parsing
        // will fail because default local may not understand what 'SEP' means
        formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
        date = LocalDate.parse("27-Sep-2015", formatter);
        System.out.println("date string : 27-Sep-2015, " + "localdate : " + date);


Output :
date string : 20150927, localdate : 2015-09-27
date string : 2015-09-27, localdate : 2015-09-27
date string : 27/09/2015, localdate : 2015-09-27
date string : 09/27/2015, localdate : 2015-09-27
date string : 27-Sep-2015, localdate : 2015-09-27

Sometimes you might get following error while parsing String to date in Java 8:

Exception in thread "main" java.time.format.DateTimeParseException: Text '27-SEp-2015' could not be parsed at index 3
at java.time.format.DateTimeFormatter.parseResolved0(
at java.time.format.DateTimeFormatter.parse(
at java.time.LocalDate.parse(
at Java8Demo.main(

It came because I was passing "SEP" instead of "Sep", so be careful with that. MMM flag in DateFormat is valid for September; Sep; 09, but anything other than that will result in above exception e.g. "SEP" or "sep" is not valid. You can also read Java SE8 for Programmers (3rd Edition) by Deietel and Deitel to learn more about Date and Time API of Java 8.

How to parse String to Date using DateTimeFormatter in Java 8

Important points

1) The SimpleDateFormat wasn't thread-safe but DateTimeFormatter is thread-safe, that's why you can safely share pre-defined format among clients.

2) If your date String contains only date part then use LocalDate.parse(), if it contains only time part then use LocalTime.parse() and if contains both date and time part then use LocalDateTime.parse() method.

3) Most important part is remembering formatting symbols e.g. d in lowercase means day of the month but D in the capital case means the day of the year, m is for minutes but M is for the month of the year. Apart from existing formatting symbols, you have got some new ones in Java 8 e.g. G for era and Q for quarter-of-year. Here is a handy table for formatting patterns from Javadoc

How to parse String to LocalDate in Java 8

That's all about how to parse and format dates in Java 8. You can also use the trick here to convert Date to String and vice-versa in Java 8 environment. You should always prefer new Date and Time API wherever you have access to JDK 8, at least for the new code you write. You can also refactor your old code to use this new library if it's practical and make sense. Also, if you are new to Java 8, you can read Java SE 8 for Really Impatient by Cay S. Horstmann to learn more about all new features. One of the most clear and concise book in Java 8.

Further Learning
The Ultimate Java 8 Tutorial
Java SE 8 New Features
From Collections to Streams in Java 8 Using Lambda Expressions

Other Java date and time tutorials you may like to explore
  • How to compare two dates in Java? (tutorial)
  • How to get current Timestamp value in Java? (tutorial)
  • How to convert String to LocalDateTime in Java 8? (example)
  • How to convert java.util.Date to java.sql.Timestamp in JDBC? (tutorial)
  • How to convert Date to LocalDateTime in Java 8? (tutorial)
  • How to get current date and time in Java 6? (tutorial)
  • How to parse String to Date using JodaTime library? (example)
  • How to convert java.util.Date to java.sql.Date in JDBC? (tutorial)

DateTimeFormatter in Java SE 8 

No comments:

Post a Comment