Pattern Symbols: Time Components (H, h, m, s, S, n, a)
What you'll learn: How to format and parse the time portion of dates using hour, minute, second, fractional second, nanosecond, and AM/PM marker symbols in DateTimeFormatter patterns.
Understanding Time Pattern Symbols
Building on date pattern symbols, time components let you control exactly how hours, minutes, seconds, and sub-second precision appear in formatted strings. These symbols work with LocalTime, LocalDateTime, ZonedDateTime, and other temporal objects containing time information.
Core Time Pattern Symbols
Hour Symbols:
H- Hour of day (0-23), 24-hour formath- Hour in AM/PM (1-12), 12-hour format
Minute and Second:
m- Minute of hour (0-59)s- Second of minute (0-59)
Sub-second Precision:
S- Fraction of second (milliseconds when 3 digits)n- Nanoseconds (full 9 digits)
AM/PM Marker:
a- AM/PM indicator
Pattern Examples
DateTimeFormatter fmt24 = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime time = LocalTime.of(14, 30, 45);
System.out.println(time.format(fmt24)); // "14:30:45"
DateTimeFormatter fmt12 = DateTimeFormatter.ofPattern("hh:mm a");
System.out.println(time.format(fmt12)); // "02:30 PM"
DateTimeFormatter fmtMillis = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
LocalTime precise = LocalTime.of(9, 15, 30, 123456789);
System.out.println(precise.format(fmtMillis)); // "09:15:30.123"
DateTimeFormatter fmtNanos = DateTimeFormatter.ofPattern("HH:mm:ss.nnnnnnnnn");
System.out.println(precise.format(fmtNanos)); // "09:15:30.123456789"
Note that single letters (like H, m) allow 1-2 digits, while doubled letters (like HH, mm) enforce zero-padding to 2 digits.
Key Takeaway: Use H for 24-hour time, h with a for 12-hour AM/PM format, m and s for minutes/seconds, S for milliseconds, and n for full nanosecond precision in your DateTimeFormatter patterns.