Java string to date conversion
To convert a string to a date in Java, you can use the parse
method of the SimpleDateFormat
class. This class allows you to specify the format of the string you are parsing, as well as the time zone and locale to be used.
Here is an example of how to use SimpleDateFormat
to parse a string and convert it to a java.util.Date
object:
String dateString = "2022-12-31";
// Set the desired format of the input string
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Parse the input string and convert it to a Date object
Date date = dateFormat.parse(dateString);
In this example, the input string has the format "yyyy-MM-dd", which corresponds to a four-digit year, followed by a two-digit month, followed by a two-digit day. The dateFormat
object is set up to parse strings in this format, and the parse
method is used to convert the input string to a Date
object.
Note that the Date
class is deprecated in Java 8 and later, so it is generally recommended to use the java.time
package (e.g., LocalDate
) instead for working with dates.