Java new date from string

In Java, you can create a new Date object from a string using the SimpleDateFormat class. Here's an example:

String dateString = "2022-07-25 14:30:00";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse(dateString);

In this example, the SimpleDateFormat object is created with a format string that matches the format of the input string. The parse() method is then called on the SimpleDateFormat object, passing in the input string as an argument. The resulting Date object represents the date and time specified in the input string.

Note that the SimpleDateFormat class is not thread-safe, so if you're using it in a multi-threaded environment, you should use a thread-safe alternative like DateTimeFormatter from the java.time package:

String dateString = "2022-07-25 14:30:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = LocalDateTime.parse(dateString, formatter);

This approach is more modern and thread-safe, and it also provides more features and flexibility than SimpleDateFormat.

Also, you can use java.time.LocalDate and java.time.LocalTime classes to parse the date and time separately:

String dateString = "2022-07-25 14:30:00";
String[] parts = dateString.split(" ");
LocalDate date = LocalDate.parse(parts[0], DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalTime time = LocalTime.parse(parts[1], DateTimeFormatter.ofPattern("HH:mm:ss"));

This approach is more flexible and allows you to parse the date and time separately, which can be useful in certain situations.