DateTimeFormatter is part of the java.time.format package. It is used to format and parse date-time objects in a thread-safe and immutable way. This API is a modern replacement for SimpleDateFormat.
LocalDate, LocalTime, LocalDateTimeA DateTimeFormatter converts date-time objects into strings and also parses strings back into date-time objects using a defined pattern.
Common pattern symbols:
yyyy – YearMM – Monthdd – DayHH – Hour (24-hour)mm – Minutesss – Seconds
// Formatting LocalDateTime using DateTimeFormatter
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterDemo {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDate = now.format(formatter);
System.out.println(formattedDate);
}
}
// Parsing a String into LocalDate using DateTimeFormatter
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateParser {
public static void main(String[] args) {
String date = "25-12-2025";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate parsedDate = LocalDate.parse(date, formatter);
System.out.println(parsedDate);
}
}
Click a Java pattern below to see how DateTimeFormatter formats the current time instantly.
dd-MM-yyyy HH:mm:ssThe first program prints the current date and time in a custom format. The second program converts a formatted string into a LocalDate object.
This demonstrates both formatting and parsing using the same formatter pattern.
DateTimeFormatter over SimpleDateFormatISO_DATE when applicableyyyy/MM/dd format