Format a Date in Java
Problem
Formatting turns a date object into text; a pattern string such as dd/MM/yyyy says which fields appear, in what order and in what style.
Display the date-time 9 March 2026, 14:05 in several common formats.
Java Program
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class FormatDate {
public static void main(String[] args) {
LocalDateTime meeting = LocalDateTime.of(2026, 3, 9, 14, 5); // 9 March 2026, 14:05
String[] patterns = {"dd/MM/yyyy", "MMMM d, yyyy", "EEE, d MMM yyyy", "hh:mm a", "yyyy-MM-dd HH:mm"};
for (String pattern : patterns) {
DateTimeFormatter f = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH); // fixed language for names
System.out.println(pattern + " -> " + meeting.format(f));
}
}
}Output
Core Logic
One LocalDateTime value can be rendered any number of ways — each DateTimeFormatter pattern is just a different view of the same moment.
- 1
LocalDateTime.of(2026, 3, 9, 14, 5)creates a fixed date-time. - 2
DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH)builds a formatter; the locale fixes the language of month and day names. - 3
meeting.format(f)produces the text for each pattern. - 4Pattern letters:
ddday,MMmonth number,MMMMmonth name,EEEshort weekday,hh/HH12-/24-hour clock,aAM/PM.
hh:mm a prints 02:05 PM, while HH:mm prints 14:05 for the same time.Key Point: Case matters: MM is month but mm is minutes, and YYYY is the week-based year, which differs from yyyy around New Year.
Key Concepts
Approach 2: Built-in ISO Formatters
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class FormatDateIso {
public static void main(String[] args) {
LocalDateTime meeting = LocalDateTime.of(2026, 3, 9, 14, 5);
System.out.println("toString(): " + meeting);
System.out.println("ISO_LOCAL_DATE: " + meeting.format(DateTimeFormatter.ISO_LOCAL_DATE));
System.out.println("ISO_LOCAL_TIME: " + meeting.format(DateTimeFormatter.ISO_LOCAL_TIME));
System.out.println("BASIC_ISO_DATE: " + meeting.format(DateTimeFormatter.BASIC_ISO_DATE));
}
}
Output
Core Logic
For machine-readable output, the predefined ISO formatters give standard text with no pattern to get wrong.
- 1
toString()on aLocalDateTimealready returns ISO-8601 text. - 2
ISO_LOCAL_DATEandISO_LOCAL_TIMEprint just the date or just the time. - 3
BASIC_ISO_DATEproduces the compactyyyyMMddform used in file names.
ISO_LOCAL_TIME includes seconds, printing 14:05:00.Key Point: Store and exchange dates in ISO format, and apply locale-specific patterns only when showing them to people.
Key Concepts
Interview Questions
Is DateTimeFormatter thread-safe?
Yes. Unlike the old SimpleDateFormat, a DateTimeFormatter is immutable and can be shared between threads as a constant.
How do you include the time zone in formatted output?
Format a ZonedDateTime and use pattern letters such as z (zone name) or XXX (offset).