Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Convert String to Date in Java
2.1.
Problem Illustration
3.
Using Instant Class to convert String to Date in Java
3.1.
CODE
3.2.
Java
4.
String to Date in Java Using Date Time Formatter Class
4.1.
CODE
4.2.
Java
5.
Using SimpleDateFormat Class to Convert String to Date in Java
5.1.
CODE
5.2.
Java
6.
Converting String to java.util.Date
6.1.
Java
7.
External Libraries
7.1.
Joda-Time Library
7.2.
Apache Commons Lang – DateUtils
7.3.
Practice Problem
8.
Frequently Asked Questions
8.1.
Can you convert string to date?
8.2.
How to convert month string to date in Java?
8.3.
How to convert string yyyy mm dd to date in Java?
8.4.
How to convert date format in Java?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

Convert String to Date in Java

Author Gaurav Joshi
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Most beginners are stuck up in Java's Conversion of String to Date. In this blog, we will look at how easily we could convert String to Date in Java with different methods hope this blog guide will help you in some ways and clear all your doubts on this topic.

Convert String to Date in Java


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

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 to convert String to Date in Java 
  2. String to Date in Java Using Date Time Formatter Class
  3. Using SimpleDateFormat Class
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Using Instant Class to convert String to Date in Java

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

  • 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);
       }
   }
}


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.

String to Date in Java 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

  • 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);
       }
   }
}

 

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.

Using SimpleDateFormat Class to Convert String to Date in Java

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

CODE

  • 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);
   }
}

 

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);
   }
}

 

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.

External Libraries

External libraries are pre-written code blocks developed by third-party developers. They provide additional functionalities and can be imported into the Java project to simplify complex tasks.

Joda-Time Library and Apache Common Langs are two examples of Java libraries that are used to convert strings to date in programs.

Joda-Time Library

Joda-Time is an open-source Java library that helps with working with dates and times. It has a more flexible API that provides an easier and more powerful way to handle dates than the standard java.util.Date and java.util.Calendar classes. Joda-Time allows programmers to format and parse dates, perform calculations, handle time zones, and work with different calendar systems.

Apache Commons Lang – DateUtils

Apache Commons Lang is a popularly used Java library that adds extra functionalities to the core Java API. The DateUtils class offers convenient methods for working with dates in Apache Commons Lang library. It enables parsing, formatting, comparing, and modifying dates. It also provides utilities for calculating date differences and adjusting time zones. Apache Commons Lang simplifies date manipulation tasks by providing ready-to-use methods and utilities.

Practice Problem

You have learned all the above methods for converting String to Date in Java. It's time for implementation. You are given the Date in the string format, and your task is based on input data to write a program that could determine if the Date is in the past, present, or future. 
Also check out Addition of Two Numbers in Java here.

Frequently Asked Questions

Can you convert string to date?

Yes, we can convert a string to a date in Java using date parsing techniques. You can do so by using the Date Time Formatter or the instant class. The parse() can be used to convert a string into java.util.date object.

How to convert month string to date in Java?

To convert a month string to a date in Java, use SimpleDateFormat with the format pattern MMMM for the month, and then parse the string into a Date object.

How to convert string yyyy mm dd to date in Java?

To convert a yyyy mm dd format string to a Date in Java, use SimpleDateFormat with pattern yyyy MM dd and parse the string into a Date object.

How to convert date format in Java?

To convert a date format in Java, use SimpleDateFormat to parse the original date, then format it into the desired format using another SimpleDateFormat.

Conclusion

The date is a format required by many applications. The same goes for the string data type. And since both appear quite the same in the output but differ in the backend, one should know how to convert a string to date in Java. This article has studied how we can convert String to Date in Java. We have explored different methods for the string-to-date conversion briefly. We expect that this article must have helped you enhance your knowledge of the topic of Java.
 

Recommended problems -

Also, visit our Guided Path in  Coding Ninjas Studio to learn about  Java. If you are preparing for an interview, visit our Interview Experience Section and interview bundle for placement preparations. Upskill yourself in Data Structures and Algorithms, JavaScript,  System Design and much more!. Please upvote our blogs if you find them engaging and helpful! 

All the best for your upcoming adventures and Happy Coding. 

Live masterclass