Java SimpleDateFormat

Profile picture for user arilio666

A class in the Java standard library called JavaSimpleDateFormat offers a flexible way to format and parse dates and times. It enables developers to generate formatted strings representing dates and times based on specific patterns and parse strings containing dates and times into Java objects.

How It Works:

  • The SimpleDateFormat class formats and parses dates and timings using a pattern string that describes the desired format. 
  • The pattern string is made up of numerous letters that indicate various components of a date or time.

Example:

       Date currentDate = new Date();
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       String formattedDate = sdf.format(currentDate);
       System.out.println("Formatted date: " + formattedDate);
        
  • Here first, we create a date and represent the current time.
  • Next, we create a SimpleDateFormat object with the required date and time format.
  • We then format the currentDate object using the created object with the SimpleDateFormat object.

Output:

Formatted date: 2023-04-20 15:59:18

Conclusion:

SimpleDateFormat is not thread-safe and should only be used in multi-threaded settings with good synchronization. Furthermore, as an alternative to SimpleDateFormat, the newer Java.time package includes more extensive and thread-safe date and time handling features beginning with Java 8.

Tags