← Back to Chapters

DateTimeFormatter

⏰ DateTimeFormatter

? Quick Overview

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.

? Key Concepts

  • Immutable and thread-safe
  • Works with LocalDate, LocalTime, LocalDateTime
  • Supports predefined and custom patterns
  • Used for both formatting and parsing

? Syntax / Theory

A DateTimeFormatter converts date-time objects into strings and also parses strings back into date-time objects using a defined pattern.

Common pattern symbols:

  • yyyy – Year
  • MM – Month
  • dd – Day
  • HH – Hour (24-hour)
  • mm – Minutes
  • ss – Seconds

? Code Example(s)

? View Code Example
// 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);
}
}
? View Code Example
// 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);
}
}

? Interactive Simulator

Click a Java pattern below to see how DateTimeFormatter formats the current time instantly.

Loading...
Current Java Pattern: dd-MM-yyyy HH:mm:ss

? Live Output / Explanation

The 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.

✅ Tips & Best Practices

  • Prefer DateTimeFormatter over SimpleDateFormat
  • Reuse formatter instances when possible
  • Always match parsing patterns exactly with input strings
  • Use predefined formatters like ISO_DATE when applicable

? Try It Yourself

  • Format the current date in yyyy/MM/dd format
  • Parse a date-time string including seconds
  • Create a formatter using 12-hour time format