W3docs

How to parse a date?

To parse a date in Java, you can use the SimpleDateFormat class.

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:


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

String dateString = "2022-01-06";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
    Date date = df.parse(dateString);
} catch (ParseException e) {
    e.printStackTrace();
}

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:


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

String dateString = "2022-01-06T10:30:00";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
    Date date = df.parse(dateString);
} catch (ParseException e) {
    e.printStackTrace();
}

This example parses a date and time string in the format "year-month-day'T'hour:minute:second".

Note: SimpleDateFormat is considered legacy. For Java 8 and later, it is recommended to use the modern java.time API with DateTimeFormatter instead.

I hope this helps. Let me know if you have any questions.