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:
DateTimeFormatter
is part of the new date-time API introduced in Java 8 (java.time
package), whileSimpleDateFormat
is part of the old date-time API (java.text
package).DateTimeFormatter
is thread-safe, it can be used by multiple threads at the same time without any issues, whileSimpleDateFormat
is not thread-safe, if you use it in multiple threads, you should create a new instance of it for each thread.DateTimeFormatter
uses 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,SimpleDateFormat
uses the locale-specific format for dates and times, which can lead to inconsistent formatting across different locales and platforms.DateTimeFormatter
class uses theChronoField
andTemporalField
enums for formatting and parsing dates and times, whileSimpleDateFormat
uses theCalendar
andDate
classes.DateTimeFormatter
is more powerful and flexible thanSimpleDateFormat
because 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.