How to convert a string to a date type in Java?
In Java, you can convert a String to a Date type using the following method:
- Utilize the parse() method in the SimpleDateFormat class:
String dateString = "2022-01-01";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(dateString);
- Utilize the parse() method of the DateTimeFormatter class (compatible with Java 8 and above):
String dateString = "2022-01-01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(dateString, formatter);
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
- Utilize the parse() method of the DateTimeFormatter class (applicable for early versions of Java 8).
String dateString = "2022-01-01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(dateString, formatter);
Date date = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
Please note that the SimpleDateFormat class of the first method is not thread-safe. If using it in a multi-threaded environment, consider using a thread-safe date formatting class such as the DateTimeFormatter class.