How to parse a date?
To parse a date in Java, you can use the SimpleDateFormat
class.
The SimpleDateFormat
class is a concrete subclass of DateFormat
that allows you to specify a pattern for the date and time format and parse a date string that matches the pattern.
Here is an example of how to use the SimpleDateFormat
class to parse a date:
String dateString = "2022-01-06";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date date = df.parse(dateString);
In this example, the parse()
method of the SimpleDateFormat
class is used to parse the date string and return a Date
object. The yyyy-MM-dd
pattern specifies that the date string should be in the format "year-month-day".
You can also use the parse()
method to parse a date and time string by specifying a pattern that includes both the date and time. For example:
String dateString = "2022-01-06T10:30:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = df.parse(dateString);
This example parses a date and time string in the format "year-month-day'T'hour:minute:second".
I hope this helps. Let me know if you have any questions.