Sub topic 10
OffsetDateTime for Storage and Data Exchange
In the last chapter you used ZonedDateTime to show a meeting time in New York and in Tokyo. That type works well when a program needs to follow a region's clock rules. When you save a time to a database or send it to another program, you usually want something simpler that has the same meaning everywhere. OffsetDateTime fills that role.
This chapter explains what OffsetDateTime is, how it differs from ZonedDateTime, and why it is a common choice for storing and sending times.
What OffsetDateTime Is
An OffsetDateTime is a date and a time of day plus a fixed offset from UTC. An offset is a number of hours and minutes ahead of or behind UTC, such as -04:00 or +09:00. In code, an offset is a ZoneOffset.
An OffsetDateTime has three parts:
- A
LocalDateTime, such as2024-07-01T09:00. - A
ZoneOffset, such as-04:00. - Together, these point to exactly one moment on the timeline, which you can get as an
Instant.
The thing it leaves out is the region name, such as America/New_York. Without a region, it knows nothing about daylight saving time. The offset stays the same unless you change it yourself.
Why Use It for Storage and Data Exchange
When you store a time or send it to another system, both sides must read it the same way. OffsetDateTime helps with this in three ways.
- It has a standard text form. ISO 8601 is the international standard for writing dates and times. It writes a moment like
2024-07-01T09:00:00-04:00. JSON APIs, log files, and many other languages use this format, andOffsetDateTimereads and writes it with no extra setup. - Databases understand it. Since JDBC 4.2, the Java database API accepts
OffsetDateTimefor SQL columns of typeTIMESTAMP WITH TIME ZONE. You callstatement.setObject(1, value)to save it andresultSet.getObject("col", OffsetDateTime.class)to read it back. - It does not depend on rule files. A region like
America/New_Yorkdepends on time zone rules that governments can change. Two computers with different rule versions could read the same region-based time differently. An offset like-04:00is a plain number, so every computer reads it the same way.
Creating an OffsetDateTime
You can build one from parts, take the current time, or parse a string. This program shows all three and reads the parts back.
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class CreateOffset {
public static void main(String[] args) {
OffsetDateTime order = OffsetDateTime.of(2024, 7, 1, 9, 0, 0, 0, ZoneOffset.ofHours(-4));
System.out.println(order); // 2024-07-01T09:00-04:00
System.out.println(order.getOffset()); // -04:00
System.out.println(order.toLocalDateTime()); // 2024-07-01T09:00
System.out.println(order.toInstant()); // 2024-07-01T13:00:00Z
OffsetDateTime parsed = OffsetDateTime.parse("2024-07-01T13:00:00Z");
System.out.println(parsed); // 2024-07-01T13:00Z
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
System.out.println(now.getOffset()); // Z
}
}The letter Z means an offset of zero, which is UTC. toString() leaves out the seconds when they are zero, so you see 09:00 and not 09:00:00.
Changing the Offset: Same Instant or Same Local Time
There are two ways to change the offset, and they do very different things.
withOffsetSameInstantkeeps the moment and changes the clock reading. Use it to convert a time to UTC before saving.withOffsetSameLocalkeeps the clock reading and changes the moment. Use it only to fix a value that was recorded with the wrong offset.
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class ChangeOffset {
public static void main(String[] args) {
OffsetDateTime order = OffsetDateTime.of(2024, 7, 1, 9, 0, 0, 0, ZoneOffset.ofHours(-4));
OffsetDateTime utcSame = order.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(utcSame); // 2024-07-01T13:00Z (same moment)
OffsetDateTime utcLocal = order.withOffsetSameLocal(ZoneOffset.UTC);
System.out.println(utcLocal); // 2024-07-01T09:00Z (a different moment, 4 hours earlier)
}
}Comparing Two OffsetDateTime Values
Two values can describe the same moment while having different offsets. The equals method compares the local date-time and the offset, so it treats them as different. The isEqual method compares only the moment.
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class CompareOffset {
public static void main(String[] args) {
OffsetDateTime a = OffsetDateTime.parse("2024-07-01T09:00:00-04:00");
OffsetDateTime b = OffsetDateTime.parse("2024-07-01T13:00:00Z");
System.out.println(a.equals(b)); // false
System.out.println(a.isEqual(b)); // true
System.out.println(a.isBefore(b)); // false
System.out.println(a.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); // 2024-07-01T09:00:00-04:00
}
}The Gotcha: Offsets Do Not Follow Daylight Saving Time
An offset never changes by itself. That makes it safe to store, but it also means date math can give a surprising result. In 2024, New York moved its clocks forward on March 10. Look at what happens when you add one day to each type.
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class OffsetVsZone {
public static void main(String[] args) {
ZoneId ny = ZoneId.of("America/New_York");
ZonedDateTime zoned = ZonedDateTime.of(2024, 3, 9, 12, 0, 0, 0, ny);
OffsetDateTime offset = zoned.toOffsetDateTime();
System.out.println(zoned.plusDays(1)); // 2024-03-10T12:00-04:00[America/New_York]
System.out.println(offset.plusDays(1)); // 2024-03-10T12:00-05:00
System.out.println(offset.plusDays(1).atZoneSameInstant(ny));
// 2024-03-10T13:00-04:00[America/New_York]
}
}ZonedDateTime knows about the clock change, so "noon tomorrow" stays at noon. OffsetDateTime keeps -05:00, so its result is 1 p.m. on a New York wall clock. If your math must follow local clock rules, convert to ZonedDateTime first, do the math, and then convert back.
Choosing Between the Types
| Need | Best type | Why |
|---|---|---|
| Save a past event, such as a login or a payment | `OffsetDateTime` or `Instant` | The moment is fixed and will never change |
| Send a time in JSON or an API | `OffsetDateTime` | ISO 8601 text with the offset included |
| Do date math that follows a region's clocks | `ZonedDateTime` | Knows daylight saving time rules |
| Plan a future event in a city, such as a meeting next year | `LocalDateTime` plus the zone ID, stored separately | If the rules change, the meeting stays at the local time people expect |
| Show a time to a user | `ZonedDateTime` | Uses the user's region |
Summary
OffsetDateTimeis a local date-time plus a fixedZoneOffset, and it points to one exact moment.- It is a good fit for databases, JSON, and logs, because its text form is standard and its meaning does not depend on rule files.
withOffsetSameInstantkeeps the moment.withOffsetSameLocalkeeps the clock reading.- Use
isEqual, notequals, to compare moments. - It does not follow daylight saving time, so do region-aware math with
ZonedDateTime.
Exercise
An API sends you the string "2024-12-01T18:30:00+01:00". Write code that parses it and prints the same moment in UTC. What does it print?
Show answer
Use OffsetDateTime.parse("2024-12-01T18:30:00+01:00").withOffsetSameInstant(ZoneOffset.UTC) and print the result. It prints 2024-12-01T17:30Z, because 18:30 at +01:00 is one hour later than UTC.
Exercise
Given OffsetDateTime a = OffsetDateTime.parse("2024-05-05T10:00+02:00") and OffsetDateTime b = OffsetDateTime.parse("2024-05-05T08:00Z"), what do a.equals(b) and a.isEqual(b) return, and why?
Show answer
a.equals(b) returns false, because the local times (10:00 and 08:00) and the offsets (+02:00 and Z) are different. a.isEqual(b) returns true, because both describe the moment 08:00 UTC.
Exercise
You need to store a dentist appointment set for 9:00 a.m. in Chicago next October. Should you store it as an OffsetDateTime? Explain.
Show answer
No. It is a future local event, and the offset for that date could change if daylight saving rules change. Store the LocalDateTime (2025-10-... 09:00) and the zone ID "America/Chicago", and combine them into a ZonedDateTime when you need the exact moment.