How to use SimpleDateFormat in Java?

The SimpleDateFormat class is used to format date and time, and can also be used to parse date and time strings. Here is a basic example of how to use SimpleDateFormat:

  1. Create a SimpleDateFormat object.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1. Format date:
Date date = new Date();
String formattedDate = sdf.format(date);
System.out.println("Formatted Date: " + formattedDate);
  1. Analyze the date:
String dateString = "2021-09-15 15:30:00";
try {
    Date parsedDate = sdf.parse(dateString);
    System.out.println("Parsed Date: " + parsedDate);
} catch (ParseException e) {
    e.printStackTrace();
}

In the above example, we first created a SimpleDateFormat object and specified the format of the date and time. Then, we used the format method to format the current date into a string with the specified format, and used the parse method to parse the string into a Date object.

It is important to note that when using SimpleDateFormat to parse dates, if the input date string format does not match the specified format, a ParseException exception will be thrown. Therefore, it is necessary to use a try-catch block for exception handling in the code block where the date is being parsed.

bannerAds