Algorithm


  1. Import Necessary Classes:

    • Import DateFormat, SimpleDateFormat, ParseException, and Date classes.
  2. Create SimpleDateFormat Object:

    • Create an instance of SimpleDateFormat with the desired date format.
  3. Parse the String:

    • Define the input string to be converted.
    • Try to parse the string using the parse method of SimpleDateFormat.
    • Handle any parsing exceptions that may occur.
  4. Use the Date Object:

    • If parsing is successful, use the resulting Date object for further processing or formatting.

 

Code Examples

#1 Code Example- Convert String to Date using predefined formatters

Code - Java Programming

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class TimeString {

    public static void main(String[] args) {
        // Format y-M-d or yyyy-MM-d
        String string = "2017-07-25";
        LocalDate date = LocalDate.parse(string, DateTimeFormatter.ISO_DATE);

        System.out.println(date);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
2017-07-25

#2 Code Example- Convert String to Date using pattern formatters

Code - Java Programming

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class TimeString {

    public static void main(String[] args) {
        String string = "July 25, 2017";

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(string, formatter);

        System.out.println(date);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
2017-07-25
Advertisements

Demonstration


Java Programing Example to Convert String to Date-DevsEnv