To convert a string to a date in Java, you can use the SimpleDateFormat
class. This class allows you to specify a format for the input string and parse it into a java.util.Date
object.
Here's an example of how to use the SimpleDateFormat
class to convert a string to a date:
String s = "2022-12-20"; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = df.parse(s); } catch (ParseException e) { e.printStackTrace(); }
In this example, we're using the yyyy-MM-dd
format, which represents a four-digit year, two-digit month, and two-digit day separated by hyphens. You can use a different format by specifying a different pattern string. For example, to use the dd/MM/yyyy
format, you can use the following code:
String s = "20/12/2022"; DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); try { Date date = df.parse(s); } catch (ParseException e) { e.printStackTrace(); }
Note that the parse
method can throw a ParseException
if the input string is not in the expected format. It's a good idea to handle this exception in a try-catch
block, as shown in the examples above.
You can find more information about the SimpleDateFormat
class and examples of how to use it in the Java documentation.