Sure! Java SimpleDateFormat is a class that allows you to format and parse dates in a specific pattern. It's part of the Java Date and Time API and provides a wide range of formatting options to customize the representation of dates and times.
Here's an example code snippet that demonstrates the usage of SimpleDateFormat:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
// Create a SimpleDateFormat instance with the desired date format pattern
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
// Format a Date object to a string representation
String formattedDate = sdf.format(new Date());
System.out.println("Formatted Date: " + formattedDate);
// Parse a string representation back to a Date object
String dateString = "2022-01-01";
Date parsedDate = sdf.parse(dateString);
System.out.println("Parsed Date: " + parsedDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
In this example, we create a SimpleDateFormat object sdf with the pattern "yyyy-MM-dd", which represents the year, month, and day in a four-digit year format, followed by a hyphen and the two-digit month and day.
We first use the format() method to format the current date new Date() into a string representation according to the specified pattern. The resulting formatted date is stored in the formattedDate variable and printed to the console.
Next, we demonstrate the parsing capability of SimpleDateFormat. We have a string dateString with the value "2022-01-01", which matches the pattern we defined earlier. Using the parse() method, we convert this string back into a Date object. The resulting parsed date is stored in the parsedDate variable and printed to the console.
It's important to handle the ParseException that may occur when parsing a string to a date, as shown in the example.
By utilizing SimpleDateFormat, you can easily customize the formatting and parsing of dates in Java according to your specific requirements.