Arithmetic with OffsetDateTime
You'll learn how to perform date-time calculations on OffsetDateTime objects while automatically preserving the UTC offset.
Core Concept
Just like LocalDateTime, OffsetDateTime supports arithmetic operations that let you add or subtract time units. The key difference is that OffsetDateTime maintains its offset throughout these calculations. When you add 5 hours to an OffsetDateTime, you get a new instance with the same offset but a different date-time value.
Think of it like adjusting a wall clock that's permanently set to a specific time zone—the clock hands move, but the zone marker stays put.
Basic Arithmetic Methods
The plusHours(), minusDays(), and similar methods work intuitively:
OffsetDateTime odt = OffsetDateTime.parse("2024-01-15T10:30:00+05:00");
OffsetDateTime later = odt.plusHours(3);
// Result: 2024-01-15T13:30:00+05:00 (offset unchanged)
OffsetDateTime earlier = odt.minusDays(2);
// Result: 2024-01-13T10:30:00+05:00 (offset unchanged)
Using Duration for Precise Arithmetic
For more complex calculations, use plus(Duration):
Duration twoHoursThirtyMin = Duration.ofHours(2).plusMinutes(30);
OffsetDateTime adjusted = odt.plus(twoHoursThirtyMin);
// Result: 2024-01-15T13:00:00+05:00
Replacing Fields with with()
The with() family of methods lets you replace specific fields while keeping everything else constant:
OffsetDateTime newYear = odt.withMonth(1).withDayOfMonth(1);
// Changes month and day, preserves time and offset
Notice that the offset always remains intact during arithmetic operations—these methods only modify the date-time portion, never the offset itself.
Key Takeaway: OffsetDateTime arithmetic methods (plusHours(), minusDays(), plus(Duration), with()) modify the date-time value while automatically preserving the original UTC offset, making them ideal for calculations where the time zone context must remain constant.