Home » Core Java » Java 8 Convert a String to LocalDate Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Java 8 Convert a String to LocalDate Example

Hello readers, in this tutorial, we will learn how to convert a given response string into a java.time.LocalDate object.

1. Introduction

These days in the programming universe Date and Time handling are the most time-consuming tasks in Java. In the ancient Java world, developers were dependent on the complex SimpleDateFormat class to convert and format the Date strings into the actual Date objects.

For meeting the Date conversion and formatting needs, JDK developers have introduced the new thread-safe DateTimeFormatter class in Java 8. Programmers will have to use the parse() method of the java.time.DateTimeFormatter class for converting a String date to a LocalDate. Let’s see the simple code snippet that shows this implementation.

Code Snippet

LocalDate date = LocalDate.parse("2017-02-05");
System.out.println("Parsed Date?= " + date);

Now, open up the Eclipse Ide and we will see how to convert a particular format Date string to a LocalDate object.

2. Java8 Convert a String to LocalDate Example

2.1 Tools Used

We are using Eclipse Oxygen, JDK 1.8 and Maven.

2.2 Project Structure

Firstly, let’s review the final project structure if you’re confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure

Fig. 1: Application Project Structure

2.3 Project Creation

This section will show how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project

Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ check-box and just click on next button to proceed.

Fig. 3: Project Details

Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters

Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code: pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Java8String2LocalDate</groupId>
	<artifactId>Java8String2LocalDate</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
</project>

Developers can start adding the dependencies that they want. Let’s start building the application!

3. Application Building

Below are the steps involved in explaining this tutorial.

3.1 Java Class Implementation

Let’s create the required Java files. Right-click on the src/main/java folder, New -> Package.

Fig. 5: Java Package Creation

Fig. 5: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.java.

Fig. 6: Java Package Name (com.jcg.java)

Fig. 6: Java Package Name (com.jcg.java)

Once the package is created in the application, we will need to create the implementation class to show the usage of parse() method of the java.time.DateTimeFormatter class. Right-click on the newly created package: New -> Class.

Fig. 7: Java Class Creation

Fig. 7: Java Class Creation

A new pop window will open and enter the file name as: StringToLocalDate. The implementation class will be created inside the package: com.jcg.java.

Fig. 8: Java Class (StringToLocalDate.java)

Fig. 8: Java Class (StringToLocalDate.java)

3.1.1 Example of converting a Date string to LocalDate object

Here is the complete Java program to show the parsing of a formatted String to a LocalDate object in Java. Do note,

  • We start by creating a Date string with value as 22-Apr-2017
  • The given date format is communicated to the Java8 Date-Time API using the ofPattern method of the DateTimeFormatter class
  • ofPattern method returns the DateTimeFormatter instance having the required date format set in it
  • Programmers pass the original date string and the date formatter as an input argument to the LocalDate.parse() method. This method returns the LocalDate instance and programmers use this object to do other operations

Let’s see the simple code snippet that shows this implementation.

StringToLocalDate.java

package com.jcg.java;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class StringToLocalDate {

	public static void main(String[] args) {

		String date = "";
		LocalDate localDate = null;
		DateTimeFormatter formatter = null;

		// Converting 'dd-MMM-yyyy' String format to LocalDate
		date = "22-Apr-2017";
		formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
		localDate = LocalDate.parse(date, formatter);
		System.out.println("Input Date?= "+ date);
		System.out.println("Converted Date?= "+ localDate + "\n");

		// Converting 'EEEE, MMM d yyyy' String format to LocalDate
		date = "Saturday, Apr 22 2017";
		formatter = DateTimeFormatter.ofPattern("EEEE, MMM d yyyy");
		localDate = LocalDate.parse(date, formatter);
		System.out.println("Input Date?= "+ date);
		System.out.println("Converted Date?= "+ localDate + "\n");

		// Converting 'dd/MM/YY' String format to LocalDate
		date = "22/04/17";
		formatter = DateTimeFormatter.ofPattern("dd/MM/yy");
		localDate = LocalDate.parse(date, formatter);
		System.out.println("Input Date?= "+ date);
		System.out.println("Converted Date?= " + localDate + "\n");

		// Converting 'YYYYMMDD' String format to LocalDate
		date = "20170422";
		formatter = DateTimeFormatter.BASIC_ISO_DATE;
		localDate = LocalDate.parse(date, formatter);
		System.out.println("Input Date?= "+ date);
		System.out.println("Converted Date?= " + localDate);
	}
}

Do remember to pass the correct MMM flag in the Date Format. The below exception trace is generated if we are passing anything other than the specified nomenclature.

Exception in thread "main" java.time.format.DateTimeParseException: Text '22-APR-2017' 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 StringToLocalDate.main(StringToLocalDate.java:15)

4. Run the Application

To run the application, developers need to right-click on the class, Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 9: Run Application

Fig. 9: Run Application

5. Project Demo

The above code shows the following logs as output.

# Logs for 'StringToLocalDate' #
================================
Input Date?= 22-Apr-2017
Converted Date?= 2017-04-22

Input Date?= Saturday, Apr 22 2017
Converted Date?= 2017-04-22

Input Date?= 22/04/17
Converted Date?= 2017-04-22

Input Date?= 20170422
Converted Date?= 2017-04-22

That’s all for this post. Happy Learning!

6. Conclusion

In this tutorial, we had an in-depth look at the Java8 LocalDate.parse() method for parsing a String to LocalDate. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you with what developers are looking for.

7. Download the Eclipse Project

This was an example of converting a String Date to LocalDate in Java8.

Download
You can download the full source code of this example here: Java8String2LocalDate
(-1 rating, 1 votes)
2 Comments Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Yatin BatraJoeHx Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
JoeHx
Guest

I was just working with Dates in Java the other day. I wish I had seen this post earlier!