Open In App

Java Program to Convert String to Date

Last Updated : 01 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string in date format, the task is to convert this String into an actual date. Here the main concept is the parse() method which helps in the conversion.

Illustration:

Input : string = "2018-10-28T15:23:01Z"
Output: 2018-10-28T15:23:01Z

Input : string = "28 October, 2018"
Output: 2018-10-28

Different Methods to Convert String to Date

  1. Using instant class
  2. Using DateTimeFormatter class
  3. Using SimpleDateFormat class

Tip: Must Read the articles DateFormat class and SimpleDateFormat Class.

Now let us discuss the above method one by one that is as follows: 

Method 1: Using Instant Class

Instant class in java.time package gives nanosecond accuracy. It is similar to the Date class but gives better accuracy.

Approach:

  1. Get the String to be converted.
  2. Create an empty Instant timestamp object.
  3. Convert the String to Date using the Instant.parse() method.
  4. If converted successfully, then print the Date.
  5. If not converted successfully, then DateTimeParseException is thrown.

Example


Output:
2018-10-28T15:23:01Z

 

Method 2: Using DateTimeFormatter Class

Approach:

  1. Get the String to be converted and the required format.
  2. Create an empty LocalDate object.
  3. Convert the String to Date using LocalDate.parse() method.
  4. If converted successfully, then print the Date
  5. If the String pattern is invalid, then IllegalArgumentException is thrown.
  6. If not converted successfully, then DateTimeParseException is thrown.

Example:


Output:
2018-10-28

 

Method 3: Using SimpleDateFormat class

Approach:

  1. Taking string input and storing it into a string
  2. Creating an object of Date class with reference to SimpleDateFormat class
  3. parsing date format into it.
  4. Print the corresponding date.

Example:


Output
29/12/96 Fri Jan 29 00:12:00 UTC 96

Output: Also when. run on the terminal, it is as follows:  


Next Article
Article Tags :
Practice Tags :

Similar Reads