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 Stream with Param

There is an overloaded version of the Stream.toArray method which can be used to return a result array that is of the same data...

Convert String to Date Using SimpleDateFormat Class

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

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

VBS Part 1 – Introduction and Background

At the upfront, this theoretical article might look boring to most of us but still, it is advisable to know about our scripting friend...

Â

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

Format Decimal Numbers Using Locale

If you want to create a DecimalFormat instance for a specific Locale, create a NumberFormat and cast it to a DecimalFormat. The java.text.DecimalFormat class is...

How To Install WordPress Locally using XAMPP

1. Introduction Installing WordPress on your computer helps you try out WordPress, test themes and plugins, and learn WordPress development.  It lets you operate a...

Maven CLI Options and Switches Reference

Maven offers a good set of commands and CLI Options to carry out wide range of Dev tasks. Most of these commands are in...

Concatenate Strings Using String.concat()

The String class has a method called concat. It accepts as parameter a String value and concatenates it with the current String. The following...

CHECKOUT TUTORIALS

Getting Started with Apache JMeter

1. Introduction As a developer, you may have tested the functionality of your code hundreds of times during development. This is known as functional testing....
- Advertisement -spot_img