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
- Using instant class
- Using DateTimeFormatter class
- 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:
- Get the String to be converted.
- Create an empty Instant timestamp object.
- Convert the String to Date using the Instant.parse() method.
- If converted successfully, then print the Date.
- If not converted successfully, then DateTimeParseException is thrown.
Example
Java
// Java Program to Convert String to Date // Using Instant Class Â
// Importing required classes import java.time.Instant; import java.time.format.DateTimeParseException; Â
// Main class class GFG { Â
    // Method     // To convert String to Date     public static Instant getDateFromString(String string)     {         // Creating an instant object         Instant timestamp = null ; Â
        // Parsing the string to Date         timestamp = Instant.parse(string); Â
        // Returning the converted timestamp         return timestamp;     } Â
    // Method 2     // Main driver method     public static void main(String[] args)     {         // Getting the string         String string = "2018-10-28T15:23:01Z" ; Â
        // Try block to check for exceptions         try { Â
            // Getting the Date from String by             // creating object of Instant class             Instant timestamp = getDateFromString(string); Â
            // Printing the converted date             System.out.println(timestamp);         } Â
        // Catch block to handle exceptions         catch (DateTimeParseException e) { Â
            // Throws DateTimeParseException             // if the string cannot be parsed             System.out.println( "Exception: " + e);         }     } } |
2018-10-28T15:23:01Z
Â
Method 2: Using DateTimeFormatter Class
Approach:
- Get the String to be converted and the required format.
- Create an empty LocalDate object.
- Convert the String to Date using LocalDate.parse() method.
- If converted successfully, then print the Date
- If the String pattern is invalid, then IllegalArgumentException is thrown.
- If not converted successfully, then DateTimeParseException is thrown.
Example:
Java
// Java program to convert String to Date // Using DateTimeFormatter Class Â
// Importing required classes import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; Â
// Main class class GFG { Â
    // Method 1     // To convert String to Date     public static LocalDate     getDateFromString(String string,                       DateTimeFormatter format)     {         // Converting the string to date         // in the specified format         LocalDate date = LocalDate.parse(string, format); Â
        // Returning the converted date         return date;     } Â
    // Method 2     // Main driver method     public static void main(String[] args)     {         // Getting the custom string input         String string = "28 October, 2018" ; Â
        // Getting the format by creating an object of         // DateTImeFormatter class         DateTimeFormatter format             = DateTimeFormatter.ofPattern( "d MMMM, yyyy" ); Â
        // Try block to check for exceptions         try { Â
            // Getting the Date from String             LocalDate date                 = getDateFromString(string, format); Â
            // Printing the converted date             System.out.println(date);         } Â
        // Block 1         // Catch block to handle exceptions occurring         // if the String pattern is invalid         catch (IllegalArgumentException e) { Â
            // Display the exception             System.out.println( "Exception: " + e);         } Â
        // Block 2         // If the String was unable to be parsed         catch (DateTimeParseException e) { Â
            // Display the exception             System.out.println( "Exception: " + e);         }     } } |
2018-10-28
Â
Method 3: Using SimpleDateFormat class
Approach:
- Taking string input and storing it into a string
- Creating an object of Date class with reference to SimpleDateFormat class
- parsing date format into it.
- Print the corresponding date.
Example:
Java
// Java Program to Convert String to Date // Using SimpleDateFormat class Â
// Importing required classes import java.text.SimpleDateFormat; import java.util.Date; Â
// Main class class GFG { Â
    // Main driver method     public static void main(String[] args) throws Exception     { Â
        // Custom string as input         String strDate = "29/12/96" ; Â
        // Creating an object of Date class with reference         // to SimpleDateFormat class and         // lately parsing the above string into it         Date date = new SimpleDateFormat( "dd/mm/yyyy" )                         .parse(strDate); Â
        // Print and display the date corresponding         // to above input string         System.out.print(strDate + " " + date);     } } |
29/12/96 Fri Jan 29 00:12:00 UTC 96
Output: Also when. run on the terminal, it is as follows: Â