How to Convert String to LocalDateTime in Java 8 - Example Tutorial

Hello guys, today, I will talk about a common problem while working in a Java application, yes you guessed it right, I am talking about String to Date conversion in Java. I had discussed this before (see the Date to String) when Java 8 was not out, but with Java 8, I don't see any reason to use old date and time API, and hence I am writing this post to teach you how to convert String to Date in Java 8 or beyond. Suppose you have a date-time String "2016-03-04: 11:01:20" and you want to convert this into a LocalDateTime object of Java 8 new date and time API, how do you do that? Well, if you have worked previously with String and Date then you know that you can parse String to Date in Java.

Before Java 8, Java developers used to use SimpleDateFormat, which was mutable and not thread-safe and advised not to be shared between threads. In Java 8 and beyond, you can use the DateTimeFormatter class to convert String to LocalDate, LocalTime, or LocalDateTime class of Java 8 Date Time API, which represents date, time, and date-time data types. 

Unlike SimpleDateFormat, the DateTimeFormatter class is both immutable and thread-safe, and you can use it as a static variable for sharing and reuse.

It also comes with a pre-defined date-time format like ISO-8601 format. The ISO_LOCAL_DATE_TIME formats or parses a date-time without an offset, such as '2016-03-04T10:15:30'.

In this article, I'll show you how to convert a String to LocalDateTime in Java 8, and then back to a formatted string, but you can also check out The Complete Java MasterClass to learn more about new Date and Time API, which is quite vast.





Converting String to LocalDateTime in Java 

In order to create a LocalDateTime object from a string, you can use the static LocalDateTime.parse() method. It takes a String and a DateTimeFormatter as a parameter.

The DateTimeFormatter argument is used to specify the date/time pattern. You can also use predefined date formats like ISO_LOCAL_DATE_TIME or can specify by yourself as String into the second parameter.

If you are new to formatting instructions, you can see the Javadoc for a complete list.

String str = "2016-03-04 11:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

Done, that's all is required to convert a formatted String to transform into a LocalDateTime. If you print or query this LocalDateTime instance, you will find that all date parts like the year, month, date, hour, and seconds are as per given input String.

Btw, If your String contains seconds as well like "2016-03-04 11:30: 40", then you can change your date time format to yyyy-MM-dd HH:mm:ss" as shown below:

String str = "2016-03-04 11:30: 40";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

These are just tip of the iceberg of what you can do with the new Date and Time API of Java 8. It's packed with powerful features which makes date and time-related task really easy in Java application. If you want to learn more, I suggest you take a look at  What's New in Java 8 course on Pluralsight.  

It's a short course, and you can learn all new Java 8 features in a quick time, which will help you to write better code In Java. 

Here is another example of formatting dates in Java 8:

DateTimeFormatter Example in Java 8


That's all about how to convert String to LocalDateTime in Java 8. As I said, you can use the java.time.DateTimeFormatter class for parsing and formatting String in Java 8.

Unlike DateFormat and SimpleDateFormat of old date and time API, this class is both immutable and thread-safe, and you can also store it into a static variable.

In the next part of this tutorial, I'll show you how to convert LocalDateTime to String in Java by formatting date into different patterns.

Further Learning
The Complete Java MasterClass
Java 8 New Features in Simple Way
From Collections to Streams in Java 8 Using Lambda Expressions


Other Java 8 and Date Time Tutorials for curious developers:
  • Java 8 Interview Questions Preparation Course (free)
  • How to convert java.util.Date to LocalDateTime in Java 8? (solution)
  • How to convert java.util.Date to java.sql.Date in JDBC? (solution)
  • How to display dates in different time zones in Java? (answer)
  • How to parse String to Date in multithreading using Joda Time? (example)
  • How to get the current date and time in Java? (example)
  • 10 Free Courses for Experienced Java Programmers (courses)
  • How to sort the may by values in Java 8? (example)
  • How to use peek() method in Java 8 (example)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • 5 Free Courses to learn Java 8 and 9 (courses)
  • My favorite courses to learn Java in-depth for FREE (courses)
  • 20 Examples of Date and Time in Java 8 (tutorial)

Thanks for reading this article so far. If you like this article, 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 just want to learn more about new features in Java 8 then please see the tutorial What's New in Java 8. It explains all the essentials features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new Date Time API, and other miscellaneous changes.


1 comment:

  1. Exception in thread "main" java.time.format.DateTimeParseException: Text '1960-12-01 0:00' could not be parsed at index 11

    ReplyDelete