Creating Custom Patterns with ofPattern
You'll learn how to build your own date and time formatting patterns using symbolic letters to represent different components.
The Core Idea
While Java provides built-in formatters like ISO_LOCAL_DATE, real applications often need custom formats—perhaps "Dec 25, 2024" or "14:30:45". The DateTimeFormatter.ofPattern() method lets you construct these by stringing together pattern symbols that represent date/time components.
Think of it like a template: you write "yyyy-MM-dd" and Java translates each symbol—yyyy becomes the four-digit year, MM becomes the two-digit month, and dd becomes the two-digit day.
Essential Pattern Symbols
Here are the building blocks you'll use most often:
yyyy– Four-digit year (2024)yy– Two-digit year (24)MM– Two-digit month (01-12)M– Month without leading zero (1-12)dd– Two-digit day (01-31)d– Day without leading zero (1-31)HH– Hour in 24-hour format (00-23)hh– Hour in 12-hour format (01-12)mm– Two-digit minute (00-59)ss– Two-digit second (00-59)
Building Your Pattern
LocalDateTime now = LocalDateTime.of(2024, 3, 5, 14, 7, 9);
DateTimeFormatter custom1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(now.format(custom1)); // 2024-03-05 14:07:09
DateTimeFormatter custom2 = DateTimeFormatter.ofPattern("M/d/yy h:mm");
System.out.println(now.format(custom2)); // 3/5/24 2:07
Notice how the number of letters matters: MM gives "03" while M gives "3". Literal characters like hyphens, slashes, and colons appear as-is in the output.
Key Takeaway: Use DateTimeFormatter.ofPattern() with symbolic letters (yyyy, MM, dd, HH, mm, ss, etc.) to create custom date/time formats—single vs. double letters control whether components have leading zeros.