How To Convert String To Date in Java

Table of Contents

Introduction

There are often scenarios in programming, where you will need to convert a date in String format to an actual Date object. For example, such a scenario may occur when the date is read from an end user via a UI and sent to the back-end code. In this article, we will understand the different ways in which you can represent a date in Java and how you can convert a String date to each of these Date representations.

Java Date Handling

Before we dive into the details of how to convert a String to a Date, let us understand how Java handles Dates.  In Java, there are three main classes that can be used to represent a date. These are as follows:

  • java.util.Date
  • java.util.Calendar
  • java.time.LocalDate

The java.util.Date and java.util.Calendar classes were present right from the early versions of Java. However, these classes have several issues. They are not very user friendly and they do not allow performing date time manipulation very easily. To address all these issues, Java 8 introduced the java.time.LocalDate class as part of DateTime API. The LocalDate class allows performing date operations easily.  So, if you have a String object, you can convert it to a java.util.Date, java.util.Calender object or a java.time.LocalDate object based on your requirements.

Converting String to java.util.Date

Sometimes, you may need to convert a String to a java.util.Date object. For this, you need to use the SimpleDateFormat class. You need to specify the format in which the String date is present and invoke the parse method. The following code demonstrates how this can be done:

private static void convertToDate() throws ParseException {
	String strDate = "2015-06-12";
	SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
	Date date = dateFormatter.parse(strDate);
	System.out.println(date);
}

This code creates a SimpleDateFormat instance. Since the input date is in the yyyy-MM-dd format, the SimpleDateFormat is created using this format. The parse() method is then invoked with the actual String date. This returns a java.util.Date object corresponding to the String. So, this code prints the following output:

Fri Jun 12 00:00:00 IST 2015

You can check out the API documentation for SimpleDateFormat in order to understand the patterns that need to be specified for various date formats.

Converting String to java.util.Calendar

As mentioned earlier, the java.util.Calendar class also encapsulates a date. The Calendar class has some more features that the java.util.Date class. It provides the ability to extract the day, month, year and other fields corresponding to the date that the Calendar represents. So, sometimes, you may need to convert a String date to a Calendar instance. For this, you first need to convert the String date to a java.util.Date instance via the SimpleDateFormat class. You can then use this Date to create a Calendar instance. The following code demonstrates this:

private static void convertToCalendar() throws ParseException {
String strDate = "2015-06-12";
	SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
	Date date = dateFormatter.parse(strDate);
	Calendar cal = Calendar.getInstance();
	cal.setTime(date);
	System.out.println(date);
}

As before, this code uses a SimpleDateFormat and creates a java.util.Date instance from the String date. The Calendar.getInstance() method is invoked which creates a Calendar object corresponding to the current time. The calendar.setTime() method is then invoked with the Date object. This changes the Calendar’s time to the time in the Date object. So, this code prints the following output:

Fri Jun 12 00:00:00 IST 2015

Converting String to java.time.LocalDate

As mentioned earlier, in order to overcome the shortcomings of the Date and Calendar classes, Java 8 introduced the LocalDate class as part of the DateTime API. Compared to the java.util.Date and java.util.Calendar classes, the LocalDate class is much simpler to use.  Let us now understand how to convert a String date to a LocalDate instance.

LocalDate without Formatter

The LocalDate class has a parse method. You can use this to convert a String to a LocalDate. The following code demonstrates this:

private static void convertToLocalDate() {
String strDate = "2015-06-12";
	LocalDate date = LocalDate.parse(strDate);
	System.out.println(date);
}

So, this code simply invokes the parse method with the String date object. It prints the following output: 2015-06-12

The LocalDate.parse() method requires the String date to be in the yyyy-MM-dd format. If the String date is in some other format, this method throws an Exception. There is an overloaded version of the parse method that can be used for such scenarios as explained in the next section.

LocalDate with formatter

The LocalDate class has an overloaded parse() method. In addition to the String Date, it accepts a DateTimeFormatter instance that specifies the format of the input date. So, this can be used in case the String date is not in the yyyy-MM-dd format. The following code demonstrates this:

private static void convertToLocalDateWithDateFormatter() { 
String strDate = "06/12/2015";
	DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
	LocalDate date = LocalDate.parse(strDate,formatter);
	System.out.println(date);
}

In this case, the String date is in the dd/MM/YYYY format.  A DateTimeFormatter instance is created with this pattern. The parse() method is then invoked with the String date and the DateTimeFormatter instance. So, this code prints the following output:

2015-06-12

You can check out the API documentation for DateTimeFormatter in order to understand the patterns that need to be specified for various date formats.

Conclusion

So, in summary, you can use the java.util.Date, java.util.Calendar or the java. time.LocalDate classes to represent a date in Java. You can convert a String date to any of these methods using the methods demonstrated in this article.

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

RELATED POSTS

Convert List to Array Using For-Loop

The simplest way to convert a List to an array is to use a for-loop. The following code snippet demonstrates this method. First, the code...

Remove Duplicates from List Using Set.addAll

The Set interface has a method called addAll. This accepts a 'Collection' as the parameter. So if you invoke this method by passing the...

Java Tutorial #6 – Jump Statements

Introduction The break statement is used to stop further execution. It can be used either in a loop or within a switch statement. Break Statement The break...

VBS Part 2 – Fundamentals and Concepts

Having gone through the Introductory part, it is time to look at some crucial fundamentals and concepts. This article is to refresh some of...

Â

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

MORE ON CODEX

MORE IN THIS CATEGORY

How To Change Font for Eclipse Editor Pane

This article shows how to change the text size and style for the Eclipse editor pane. The font used for Eclipse editor pane can be...

How To Concatenate Strings in Java

Introduction In Java, a String is a sequence of characters. There are often programming situations where you will need to concatenate Strings. There are several...

Create Basic Hibernate Program

Hibernate is an ORM framework that helps in accessing database tables from Java code. It is an object-oriented way of accessing database tables and...

Java Tutorial #3 – Java Arrays

Table of Contents One Dimensional Array Declaring Array Allocting Memory to Array Accessing Array Elements Initializing Array Length of Array Multi Dimensional Array Creating 3...

CHECKOUT TUTORIALS

Java Tutorial #6 – Jump Statements

Introduction The break statement is used to stop further execution. It can be used either in a loop or within a switch statement. Break Statement The break...
- Advertisement -spot_img