Table of contents
1.
Introduction
2.
How to Convert String to Date in Java?
2.1.
Problem Illustration
3.
Method 1 - Converting String to Date in Java by using Instant Class
3.1.
Java
4.
Method 2 - Converting  String to Date in Java by Using Date Time Formatter Class
4.1.
Java
5.
Method 3 - Converting String to Date in Java by Using SimpleDateFormat Class
5.1.
Java
6.
Converting String to java.util.Date
6.1.
Java
7.
Frequently Asked Questions
7.1.
What is the difference between SimpleDateFormat and DateTimeFormatter?
7.2.
Can I convert both date and time from a string using DateTimeFormatter?
7.3.
Why should I prefer DateTimeFormatter over SimpleDateFormat?
7.4.
Can I use DateTimeFormatter with Date objects?
8.
Conclusion
Last Updated: Jan 7, 2025
Medium

Convert String to Date in Java

Author Gaurav joshi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will explore how to convert strings to date formats in Java, a common requirement for date manipulation in applications. We will discuss various methods, including using the SimpleDateFormat and DateTimeFormatter classes. By the end, you will have a clear understanding of how to effectively handle date conversions, ensuring your applications can manage date and time data seamlessly.

Convert String to Date in Java


Also Read About, Multithreading in java, and Duck Number in Java.

How to Convert String to Date in Java?

So you are given a string in date format. The format for the Date could be YYYY/MM/DD or DD/MM/YYYY. Our task here is to convert these String to Date in Java. The parse() method is a significant concept that will help us through this conversion. 

Problem Illustration

Example 01

Input
String = “2022-07-17”

Output
2022-07-17

 

Example 02

Input
String = “17July,2022”

Output
2022-07-17

 

Let us look into different methods we could do the task.

  1. Using Instant Class
  2. Using Date Time Formatter Class
  3. Using SimpleDateFormat Class

Method 1 - Converting String to Date in Java by using Instant Class

In this method, we would use the Instant class defined in Java.Time package with nanosecond accuracy. This Instant Class is very similar to the Date class but gives better accuracy than that. Here We Would be Getting Conversion of String to Date in Java. First, we would be Creating an empty Instant datatype object. After the Instant Class Object is Created, We would Convert the String to Date using the Instant.parse() method. If No Exception is raised, It will then print the Date. Else If not converted successfully, then it will raise DateTimeParseException.

Code Implementation

  • Java

Java

// Convert String to Date in Java Utilizing Instant Class

// First we would Import All classes that are required classes
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.Date;

//Define our Main class
class CodingNinja {

   //Public Method for converting String to Date in Java
   public static Instant convertStringToDate(String input)
   {
       // Creating an instant object
       Instant dateType = null;

       // Parsing the string to Date
       dateType = Instant.parse(input);

       // Returning the converted dateType
       return dateType;
   }

   // Method 2
   // Main driver method
   public static void main(String[] args)
   {
       // Getting the string in date format
       String input = "2022-07-17T00:00:00Z";
       System.out.println("Input :\n"+input);
       System.out.println("Output :");



       // Try block to check for exceptions raised if String is not in date format)
       try {

           // We need to Get the Date from String by creating an object of Instant class
           Instant dateType = convertStringToDate(input);
           System.out.println("Date Format");
           // Printing the converted date
           System.out.println(dateType);
          
       }

       // Using Catch block for handling exceptions raised during execution
       catch (DateTimeParseException e) {

           // If we are not able tp parse String raise DateTimeParseException
           System.out.println("Not in Date Format");
           System.out.println("Exception: " + e);
       }
   }
}
You can also try this code with Online Java Compiler
Run Code


Output

Input :
2022-07-17T00:00:00Z
Output :
Date Format
2022-07-17T00:00:00Z

 

Explanation

In this example, the code demonstrates converting a string representation of a date into a Date object using the Instant class from the java.time package. It imports necessary classes and defines a method, convertStringToDate, which parses the input string into an Instant object. In the main method, a sample date string is printed, converted using convertStringToDate, and printed again. If the input string is not in the correct format, an error message is printed.
You can easily run this code yourself with java online compiler.

Method 2 - Converting  String to Date in Java by Using Date Time Formatter Class

Convert the Given String to Date in Java in the required format. First, we would Create an empty LocalDate object. Then we would Convert the String to Date in Java using the LocalDate.parse() method. If we successfully convert the String to Date, we would then print the Date. Else will raise IllegalArgumentException or DateTimeParseException.

Code Implementation

  • Java

Java

// Utilizing DateTimeFormatter Class to Convert String to Date in Java

// Importing all the required classes
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

// Define Main class
class CodingNinja {

   // Method 1 :- Convert String to Date in Java
   public static LocalDate convertDateToString(String input,DateTimeFormatter format)
   {
       // String to Date Conversion in the specified format
       LocalDate date = LocalDate.parse(input, format);

       // Returning the converted Date
       return date;
   }

   // Method 2
   // Main driver method
   public static void main(String[] args)
   {
       // Getting the custom string input
       System.out.println("Input : ");
       String input = "18 July, 2022";
       System.out.println(input+"\n");

       // Creating an object of the DateTImeFormatter class
       DateTimeFormatter format = DateTimeFormatter.ofPattern("d MMMM, yyyy");

       // Try block to check for exceptions
       try {

           // Getting the Date from String
           LocalDate date = convertDateToString(input, format);

           // Printing the converted date
           System.out.println("Output :");
           System.out.println(date);
       }

       // Catch Block 1
       // Catch Exception If String Pattern is Found invalid
       catch (IllegalArgumentException e) {

           // Display the exception
           System.out.println("Invalid Date Pattern");
           System.out.println("Exception: " + e);
       }

       // Catch Block 2
       // If we are not able to parsed the String
       catch (DateTimeParseException e) {

           // Display the exception
           System.out.println("Invalid Date Pattern");
           System.out.println("Exception: " + e);
       }
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

Input : 
18 July, 2022

Output :2022-07-18

 

Explanation

In this example, the code demonstrates converting a string representation of a date into a LocalDate object using DateTimeFormatter from the java.time.format package. It imports necessary classes, including LocalDate, DateTimeFormatter, and DateTimeParseException. The method convertDateToString takes a string input and a DateTimeFormatter object to parse the input string into a LocalDate object. In the main method, a sample date string is printed, converted using convertDateToString, and printed again. Exception handling is included to catch format mismatches.

Method 3 - Converting String to Date in Java by Using SimpleDateFormat Class

We would Parse Input String into a Simple date Class object concerning SimpleDateFormat class and Print the corresponding Date.

Code Implementation

  • Java

Java

// Using SimpleDateFormat Class to Convert String to Date in Java

// Import Classes Required
import java.text.SimpleDateFormat;
import java.util.Date;

// Main class
public class Main {

   // Define main method
   public static void main(String[] args) throws Exception
   {

       // Taking String as Our Input
       String input = "17/07/2022";
       System.out.println("Input : ");
       System.out.println(input +"\n");

       // Parse Above String into a Simple date Class object with reference
       // to SimpleDateFormat class
       Date input_date = new SimpleDateFormat("dd/MM/yyyy").parse(input);

       // Print and display the date corresponding
       // to above input string
       System.out.println("Output : ");
       System.out.println(input_date);
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

Input : 
17/07/2022
Output : Sun Jul 17 00:00:00 GMT 2022

 

Explanation

In this example, the code demonstrates how to convert a string representation of a date into a Date object using the SimpleDateFormat class from the java.text package. It imports the necessary classes, SimpleDateFormat and Date. In the main method of the Main class, a sample date string ("17/07/2022") is assigned to the input variable and printed. Then, SimpleDateFormat is utilized to parse the input string into a Date object using the pattern "dd/MM/yyyy". Finally, the parsed Date object is printed. While this approach provides a simple method for date conversion, it's important to note that SimpleDateFormat is not thread-safe, which may lead to issues in a multi-threaded environment.

Converting String to java.util.Date

The SimpleDateFormat class can be used to convert a string to a java.util.Date object in Java. This class provides methods to parse a string representing a date and time according to a specified format pattern. By using the parse() method, you can convert a string into a Date object.

Example

  • Java

Java

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDateConvert {
   public static void main(String[] args) throws ParseException {
       String dateInString = "2023-07-03";
       
       DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
       Date date = dateFormat.parse(dateInString);
      
       System.out.println("Converted Date: " + date);
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

Converted Date: Mon Jul 03 00:00:00 GMT 2023Converting String to java.util.Date

 

Explanation

In this example, the code converts a string date ("2023-07-03") into a Date object using SimpleDateFormat. It initializes a SimpleDateFormat object with the pattern "yyyy-MM-dd" to match the input string format and parses the string into a Date object using the parse method. Finally, the converted date is printed.

Frequently Asked Questions

What is the difference between SimpleDateFormat and DateTimeFormatter?

SimpleDateFormat is part of the legacy date-time API and is not thread-safe, while DateTimeFormatter is part of the modern Java Date and Time API introduced in Java 8. DateTimeFormatter is immutable and thread-safe, making it a better choice for concurrent applications.

Can I convert both date and time from a string using DateTimeFormatter?

Yes, you can convert both date and time from a string using DateTimeFormatter. It allows you to parse date-time strings into LocalDateTime, LocalDate, or LocalTime objects, enabling flexible handling of various date-time formats.

Why should I prefer DateTimeFormatter over SimpleDateFormat?

You should prefer DateTimeFormatter over SimpleDateFormat because it offers better thread safety, immutability, and a more flexible API. Additionally, it integrates seamlessly with the modern Java Date and Time API, improving overall code readability and maintainability.

Can I use DateTimeFormatter with Date objects?

No, DateTimeFormatter cannot be used directly with Date objects, as it is designed for the new Java Time API. However, you can convert Date objects to LocalDateTime or other types before using DateTimeFormatter for formatting or parsing.

Conclusion

In this article, we have discussed how to convert strings to dates in Java using both SimpleDateFormat and DateTimeFormatter. We explored their differences, usage, and advantages, providing you with the knowledge to handle date conversions effectively in your Java applications. 

Recommended problems -

Live masterclass