how to convert java string to Date object

To convert a string to a Date object in Java, you can use the parse() method of the SimpleDateFormat class. The SimpleDateFormat class provides a formatter for parsing and formatting dates in a locale-sensitive manner.

Here is an example of how you can use the parse() method to convert a string to a Date object:

String str = "2022-01-01";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(str);

The SimpleDateFormat class uses a pattern to define the format of the date string. In the example above, the pattern "yyyy-MM-dd" specifies that the date string has a four-digit year (yyyy), a two-digit month (MM), and a two-digit day (dd).

You can specify a different pattern to match the format of the date string, or you can use the default pattern of the SimpleDateFormat class.

Keep in mind that the parse() method throws a ParseException if the date string cannot be parsed according to the pattern. You should handle this exception or use the try-catch statement to catch it.

For example:

String str = "2022-01-01";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
    Date date = dateFormat.parse(str);
} catch (ParseException e) {
    // handle the exception
}

Alternatively, you can use the DateTimeFormatter class from the java.time package to parse a date string. The DateTimeFormatter class is immutable and thread-safe, and it provides support for formatting and parsing dates and times in a variety of formats.

Here is an example of how you can use the DateTimeFormatter class to parse a date string:

String str = "2022-01-01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(str, formatter);

The DateTimeFormatter class uses a pattern to define the format of the