Formatting and Parsing OffsetDateTime
You'll learn how to convert OffsetDateTime to strings and parse strings back into OffsetDateTime objects using DateTimeFormatter.
The Core Idea
Just like you need a specific address format when mailing letters internationally (including country codes), OffsetDateTime needs proper formatting to display or parse date-time values that include UTC offset information. Java's DateTimeFormatter provides built-in patterns and lets you create custom ones to handle this conversion in both directions.
Using ISO_OFFSET_DATE_TIME
The DateTimeFormatter class includes a predefined formatter specifically for OffsetDateTime:
OffsetDateTime odt = OffsetDateTime.now();
// Format to string
String formatted = odt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
// Example: "2024-03-15T14:30:45.123+02:00"
// Parse from string
OffsetDateTime parsed = OffsetDateTime.parse("2024-03-15T14:30:45+02:00");
The ISO_OFFSET_DATE_TIME pattern follows ISO-8601 standard and automatically includes the offset.
Custom Formatting Patterns
You can create custom patterns when you need specific output:
DateTimeFormatter custom = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX");
OffsetDateTime odt = OffsetDateTime.of(2024, 3, 15, 14, 30, 0, 0, ZoneOffset.ofHours(2));
// Format
String result = odt.format(custom);
// Result: "2024-03-15 14:30:00 +02:00"
// Parse
OffsetDateTime parsed = OffsetDateTime.parse("2024-03-15 14:30:00 +02:00", custom);
The XXX pattern symbol represents the offset with a colon (like +02:00), while XX omits the colon (+0200).
Key Takeaway: Use DateTimeFormatter.ISO_OFFSET_DATE_TIME for standard formatting or create custom patterns with ofPattern(), ensuring your pattern includes offset symbols like XXX to preserve the UTC offset information when formatting and parsing OffsetDateTime.