Thursday, September 2, 2021

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 objects 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.

The same is true while formatting Date to String. Java is very flexible in terms of various 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 like 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. Btw, if you are new to Java and not familiar with various date formats and data types like Date and String, then I suggest you join a comprehensive course like The Complete Java MasterClass on Udemy to cover your base.

It is also updated for Java 11 recently and will be updated for Java 12 as per its track record.





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 the 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 the 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(DateTimeFormatter.java:1948)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1850)
at java.time.LocalDate.parse(LocalDate.java:400)
at Java8Demo.main(Java8Demo.java:57)

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 the above exception e.g. "SEP" or "sep" is not valid.

You can also check out the What's New in Java 8 course on Pluaralsightto to learn more about the Date and Time API of Java 8.

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






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 the 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) The most important part is remembering formatting symbols e.g. d in lowercase means the 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 like 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 a 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.


Other Java date and time tutorials you may like to explore
  • How to compare two dates in Java? (tutorial)
  • Top 10 Courses to learn Java for Beginners (courses)
  • 5 Books to Learn Java 8 Better? (read here)
  • How to get the current Timestamp value in Java? (tutorial)
  • Top 5 Courses to become a full-stack Java developer (courses)
  • How to convert String to LocalDateTime in Java 8? (example)
  • 10 Free Courses to learn Spring Framework (courses)
  • How to convert java.util.Date to java.sql.Timestamp in JDBC? (tutorial)
  • How to convert Date to LocalDateTime in Java 8? (tutorial)
  • Top 7 Courses to learn JVM in-depth (courses)
  • How to get the current date and time in Java 6? (tutorial)
  • Top 5 Course to master Java 8 Programming (courses)
  • How to parse String to Date using the JodaTime library? (example)
  • How to convert java.util.Date to java.sql.Date in JDBC? (tutorial)
  • 5 Free courses to learn Java 8 and Java 9 (courses)
  • 10 Java 9 tutorials to learn new features (tutorials)

Thanks for reading this article so far. If you find this Java 8 String to LocalDate conversion tutorial useful then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are serious about learning Java 8 Functional programming but looking for a free online training course to start with then you can also check out this Java 8 Functional Programming: Lambda Expressions Quickly course on Udemy. It's completely free and you just need a Udemy account to join this course.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.