DateTimeFormatter and SimpleDateFormat are both classes in Java that are used to format and parse dates and times. However, there are some key differences between them:
DateTimeFormatteris part of the new date-time API introduced in Java 8 (java.timepackage), whileSimpleDateFormatis part of the old date-time API (java.textpackage).DateTimeFormatteris thread-safe, it can be used by multiple threads at the same time without any issues, whileSimpleDateFormatis not thread-safe, if you use it in multiple threads, you should create a new instance of it for each thread.DateTimeFormatteruses the ISO-8601 standard for formatting and parsing dates and times, which means that the format of the date and time is consistent across different locales and platforms. On the other hand,SimpleDateFormatuses the locale-specific format for dates and times, which can lead to inconsistent formatting across different locales and platforms.DateTimeFormatterclass uses theChronoFieldandTemporalFieldenums for formatting and parsing dates and times, whileSimpleDateFormatuses theCalendarandDateclasses.DateTimeFormatteris more powerful and flexible thanSimpleDateFormatbecause it supports additional features such as formatting and parsing using fields, parsing using predefined formats, and formatting using predefined styles.
Here is an example of how to use DateTimeFormatter to format a LocalDateTime object:
LocalDateTime dateTime = LocalDateTime.of(2022, Month.JANUARY, 1, 12, 30, 45);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = dateTime.format(formatter);
Here is an example of how to use SimpleDateFormat to format a Date object:
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(date);
In general, it’s recommended to use DateTimeFormatter when working with the new date-time API in Java 8 and later, while SimpleDateFormat is still useful when working with the old date-time API (java.util.Date and java.util.Calendar) in Java 7 and earlier.