Avatar ·

Converting string to date in Java: how to correctly parse a date from a string?

Hello everyone! I'm a beginner in Java and have been struggling with a problem for several hours. I need to convert the string "2023-05-15 14:30:00" to a Date object. I tried using SimpleDateFormat, but nothing works. Here is my code:
String dateStr = "2023-05-15 14:30:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateStr);
The compiler complains about an uncaught ParseException. I added throws ParseException to the main method, but now the program just crashes with an error. I tried different formats — "dd.MM.yyyy", "MM/dd/yyyy" — still an error. I also heard that SimpleDateFormat is not thread-safe, but I'm working in a single thread for now. Maybe the problem is that I have Java 8? I read that a new API java.t