Algorithm
-
Import Necessary Classes:
- Import
DateFormat
,SimpleDateFormat
,ParseException
, andDate
classes.
- Import
-
Create SimpleDateFormat Object:
- Create an instance of
SimpleDateFormat
with the desired date format.
- Create an instance of
-
Parse the String:
- Define the input string to be converted.
- Try to parse the string using the
parse
method ofSimpleDateFormat
. - Handle any parsing exceptions that may occur.
-
Use the Date Object:
- If parsing is successful, use the resulting
Date
object for further processing or formatting.
- If parsing is successful, use the resulting
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
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
2017-07-25
Demonstration
Java Programing Example to Convert String to Date-DevsEnv