Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaJava Program to Convert String to Date

Java Program to Convert String to Date

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

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


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:

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


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:

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


Output

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

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

RELATED ARTICLES

Most Popular

Recent Comments