Convert String to Date in Java - GeeksforGeeks

29 Oct, 2021
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
Methods:
Using instant classUsing DateTimeFormater classUsing SimpleDateFormat class
Using instant class
Using DateTimeFormater class
Using SimpleDateFormat class
Now let us discuss 
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 objectConvert the String to Date using the Instant.parse() method.If converted successfully, then print the DateIf not converted successfully, then DateTimeParseException is thrown.
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 // Importing required classesimport java.time.Instant;import java.time.format.DateTimeParseException; // Main classclass 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 objectConvert the String to Date using LocalDate.parse() method.If converted successfully, then print the DateIf the String pattern is invalid, then IllegalArgumentException is thrown.If not converted successfully, then DateTimeParseException is thrown.
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 // Importing required classesimport java.time.LocalDate;import java.time.format.DateTimeFormatter;import java.time.format.DateTimeParseException; // Main classclass 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 tp 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 occuring        // 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
Procedure:
Taking string input and storing it into a stringCreating an object of Date class with reference to SimpleDateFormat classparsing date format into it .Print the corresponding date.
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 // Importing required classesimport java.text.SimpleDateFormat;import java.util.Date; // Main classclass 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);    }}
Output:
sumitgumber28
sagar0719kumar
solankimayank
surindertarika1234
date-time-program
Java-Date-Time
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
HashMap containsKey() Method in Java
How to Create Array of Objects in Java?
Convert Double to Integer in Java
Iterating over ArrayLists in Java
Generating random numbers in Java