Java Programming

Optional and the java.time API: Handling Absence and Dates Correctly

Intermediate7 min readUpdated

Two Java 8 APIs fixed long-standing sources of bugs: Optional gives a type for 'maybe absent' so callers cannot forget the empty case, and java.time replaces the mutable, zone-confused Date and Calendar classes with immutable, clearly named types. This guide explains what each type means, the operations you will use daily, how to convert between them, and the mistakes — Optional fields, LocalDateTime for timestamps, shared SimpleDateFormat instances — that keep appearing in code reviews.

What you will learn

  • Use Optional as a return type and chain map, flatMap, filter and orElse without calling get
  • Explain the difference between Instant, LocalDateTime, ZonedDateTime and OffsetDateTime
  • Choose Duration or Period correctly and perform date arithmetic that respects time zones
  • Format and parse dates with DateTimeFormatter, including ISO-8601
  • Convert between java.time, epoch milliseconds, java.util.Date and JDBC types

Two categories of bug were endemic in Java code before Java 8: the NullPointerException from a method that returned null to mean "nothing found" and the caller who forgot to check, and the date that was silently wrong by an hour, a day or a time zone because java.util.Date was a mutable millisecond count pretending to be a calendar. Optional and java.time are the responses. Both are small APIs, and both have well-established rules for use that this guide sets out. Code targets Java 21.

Optional: a type for "maybe absent"

Optional<T> is a container that either holds a non-null value or is empty. Its purpose is narrow: as a return type, it tells the caller in the signature that a result may be missing, and its API pushes them to handle that case where they would have skipped a null check.

public Optional<Customer> findByEmail(String email) {
    Customer c = index.get(email.toLowerCase());
    return Optional.ofNullable(c);              // empty if null
}

// Caller
String greeting = findByEmail("[email protected]")
        .map(Customer::firstName)               // Optional<String>, still empty if no customer
        .filter(name -> !name.isBlank())
        .map(name -> "Hello, " + name)
        .orElse("Hello");

Create one with Optional.of(value) (throws on null), Optional.ofNullable(value) or Optional.empty(). Then consume it through the combinators rather than by inspection:

MethodUse
map(fn)Transform the value if present; result is Optional<R>
flatMap(fn)Like map when fn itself returns an Optional, avoiding Optional<Optional<R>>
filter(pred)Becomes empty if the predicate fails
orElse(v)The value or a fallback; v is always evaluated
orElseGet(supplier)The value or a lazily computed fallback
orElseThrow() / orElseThrow(supplier)The value or an exception (no-arg form throws NoSuchElementException)
ifPresent(consumer) / ifPresentOrElse(consumer, runnable)Side effects for each case
or(supplier)Another Optional if this one is empty (Java 9)
stream()Zero-or-one-element stream, handy inside flatMap (Java 9)

orElse versus orElseGet matters when the fallback is expensive: orElse(loadDefault()) calls loadDefault() every time, even when the value is present.

isPresent() followed by get() is the pattern to unlearn. It is a null check with more characters, and get() throws NoSuchElementException on empty, which is no better than an NPE. get() was retained for compatibility; orElseThrow() says the same thing honestly.

Where Optional does not belong

  • Fields. Optional is not Serializable, costs an allocation per object, and the field can still be null. Use a nullable field and return Optional.ofNullable(field) from the accessor if you want callers to see the absence.
  • Method parameters. Callers must wrap every argument. Provide an overload or accept a nullable value.
  • Collections. List<Optional<String>> and Optional<List<String>> are both worse than a list that is simply empty.
  • Performance-critical paths. It is an object; in a tight loop returning null with a documented contract, or a primitive sentinel, may be justified. OptionalInt, OptionalLong and OptionalDouble exist for primitive results and are what IntStream.max() returns.

A useful test: if you could not express the code with map, flatMap, filter and one terminal orElse*, you are probably using Optional as a glorified null.

java.time: the model

The pre-Java 8 classes had one type, Date, for every concept, and it was mutable, zero-based in its months and secretly UTC. java.time gives each concept its own immutable type. Learning which one to use is most of the work.

TypeRepresentsExampleUse for
InstantA point on the UTC timeline2026-09-07T10:15:30ZTimestamps, logs, "when did it happen"
LocalDateA calendar date, no time, no zone2026-09-07Birthdays, due dates, business days
LocalTimeA wall-clock time, no date, no zone10:15:30Opening hours, alarms
LocalDateTimeDate and time, no zone2026-09-07T10:15:30Values that are intentionally zone-free (a recurring 09:00 meeting)
ZonedDateTimeDate, time and a region zone with DST rules2026-09-07T10:15:30+02:00[Europe/Paris]Displaying to a user, scheduling in a region
OffsetDateTimeDate, time and a fixed UTC offset2026-09-07T10:15:30+02:00Interchange (JSON, databases) where the offset is known but the region is not
DurationAmount of time in seconds/nanosPT1H30MTimeouts, elapsed time
PeriodAmount of time in years/months/daysP1M10DSubscription lengths, age
ZoneId / ZoneOffsetA region (Europe/Paris) or fixed offset (+02:00)Converting between the above
Year, YearMonth, MonthDay, DayOfWeek, MonthPartial dates2026-09Credit-card expiry, reports

The single most important distinction: a LocalDateTime is not a moment. "2026-03-29T02:30" does not exist in Paris (the clocks skip it) and "2026-10-25T02:30" happens twice. Only Instant, ZonedDateTime and OffsetDateTime identify a unique moment. Store and transmit Instant (or OffsetDateTime where the API demands an offset); use ZonedDateTime when a human's local calendar matters; use LocalDateTime only when the absence of a zone is the point.

Instant now = Instant.now();                                          // UTC, from the system clock
ZonedDateTime paris = now.atZone(ZoneId.of("Europe/Paris"));          // same moment, local view
LocalDate today = paris.toLocalDate();                                // the date in Paris
ZonedDateTime nextNine = paris.plusDays(1).withHour(9).withMinute(0).withSecond(0).withNano(0);
Instant back = nextNine.toInstant();                                  // for storage

All these types are immutable: plusDays returns a new object and leaves the original untouched. Forgetting to use the return value is a common silent bug: date.plusDays(1); on its own does nothing.

Clocks and testability

Instant.now(), LocalDate.now() and friends read the system clock, which makes code using them impossible to test deterministically. Every now() has an overload taking a Clock; inject one (Clock.systemUTC() in production, Clock.fixed(instant, zone) in tests) and time-dependent logic becomes a pure function of its inputs.

Arithmetic: Duration versus Period

Duration measures elapsed time exactly; Period measures calendar distance. Adding a Duration of 24 hours to a ZonedDateTime across a DST change gives a different wall-clock time; adding a Period of one day gives the same wall-clock time on the next date. Both are correct — for different questions.

ZonedDateTime beforeShift = ZonedDateTime.of(2026, 10, 24, 12, 0, 0, 0, ZoneId.of("Europe/Paris"));
beforeShift.plus(Duration.ofHours(24));   // 2026-10-25T11:00+01:00 — 24 real hours later
beforeShift.plus(Period.ofDays(1));       // 2026-10-25T12:00+01:00 — same time next day

Duration elapsed = Duration.between(start, Instant.now());    // for timing
long ms = elapsed.toMillis();

Period age = Period.between(LocalDate.of(1990, 4, 12), LocalDate.now());
int years = age.getYears();

long daysUntil = ChronoUnit.DAYS.between(LocalDate.now(), deadline);   // whole units between two temporals

ChronoUnit.X.between(a, b) is the idiom for "how many whole units apart", and it truncates rather than rounds. LocalDate arithmetic clamps to the end of the month: 31 January plus one month is 28 (or 29) February, and adding another month gives 28 March, not 31 — a Period of two months applied at once gives 31 March. If month-end behaviour matters, compute from the original date.

Formatting and parsing

DateTimeFormatter handles both directions and is immutable, so keep one in a static final field. The predefined ISO formatters cover interchange formats:

static final DateTimeFormatter HUMAN = DateTimeFormatter.ofPattern("EEEE d MMMM uuuu, HH:mm", Locale.UK);

String iso = Instant.now().toString();                        // 2026-09-07T10:15:30.123456Z
String forUser = ZonedDateTime.now(ZoneId.of("Europe/London")).format(HUMAN);
                                                              // Monday 7 September 2026, 11:15

LocalDate d = LocalDate.parse("2026-09-07");                 // ISO_LOCAL_DATE by default
Instant i = Instant.parse("2026-09-07T10:15:30Z");
OffsetDateTime o = OffsetDateTime.parse("2026-09-07T12:15:30+02:00");
LocalDate custom = LocalDate.parse("07/09/2026", DateTimeFormatter.ofPattern("dd/MM/uuuu"));

Pattern letters to get right: uuuu is the proleptic year and is safer than yyyy (year-of-era, which needs an era to be unambiguous in strict mode); MM is month and mm is minute; HH is 24-hour, hh needs a for AM/PM; EEEE is the full day name. Always pass a Locale when the pattern includes names, otherwise output depends on the server's default locale.

Parsing is strict by default with the ISO formatters and ResolverStyle.SMART with patterns, which accepts 31 April as 30 April. Use .withResolverStyle(ResolverStyle.STRICT) (and uuuu, since strict yyyy requires an era) when invalid dates must be rejected. A DateTimeParseException — unchecked — reports the index of the failure.

For APIs, emit ISO-8601 with an offset or Z (the profile defined in RFC 3339). Jackson serialises Instant as an ISO string once the jackson-datatype-jsr310 module is registered and WRITE_DATES_AS_TIMESTAMPS is disabled — Spring Boot does both; with the module alone you get a decimal-seconds number, and without it recent Jackson versions refuse to serialise the type.

Interoperating with legacy and external types

You will meet java.util.Date in old libraries, JDBC drivers and Calendar-based code. Convert at the boundary and keep java.time everywhere else:

Date legacy = Date.from(instant);
Instant fromLegacy = legacy.toInstant();

long epochMillis = instant.toEpochMilli();
Instant fromMillis = Instant.ofEpochMilli(epochMillis);
long epochSeconds = instant.getEpochSecond();

// JDBC 4.2+: pass java.time types directly
preparedStatement.setObject(1, offsetDateTime);          // TIMESTAMP WITH TIME ZONE
LocalDate d = resultSet.getObject("due_date", LocalDate.class);

java.sql.Timestamp, java.sql.Date and java.sql.Time are subclasses of java.util.Date with even stranger behaviour (java.sql.Date throws on time-of-day methods) and should not appear in application code; JDBC 4.2 and every current driver accept LocalDate, LocalTime, LocalDateTime, OffsetDateTime and Instant through setObject/getObject. For epoch values in JSON or logs, the timestamp converter turns milliseconds into readable dates while debugging.

Time-zone data is shipped inside the JDK (the tzdata rules) and updated with JDK patch releases. Governments change DST rules with short notice; an unpatched JDK computes wrong local times for those regions.

Common mistakes

Optional.get() without a check. Throws NoSuchElementException; use orElseThrow with a meaningful exception or a combinator.

Optional fields, parameters and collections. Wrong tool; see above.

LocalDateTime for a timestamp. It records no zone, so the moment is ambiguous and DST transitions produce impossible or duplicate values. Store Instant.

Ignoring the return value. date.plusDays(1); discards the result because every java.time type is immutable.

Sharing SimpleDateFormat. It is mutable and not thread-safe; two threads corrupt each other's output. DateTimeFormatter is safe to share.

yyyy with strict parsing. Year-of-era needs an era; use uuuu.

Comparing ZonedDateTime with equals. Two objects for the same instant in different zones are not equals. Use isEqual, isBefore, isAfter, or compare toInstant().

Assuming a day is 24 hours. Use Period for calendar days and Duration for elapsed hours; do not multiply out 86_400_000.

ZoneId.systemDefault() in server code. It depends on where the JVM runs. Pass the user's or the business's zone explicitly and run servers in UTC.

Key takeaways

  • Optional is a return type that makes absence explicit; consume it with map, flatMap, filter and orElse*, never with isPresent/get, and keep it out of fields, parameters and collections.
  • Only Instant, ZonedDateTime and OffsetDateTime denote a unique moment; LocalDateTime is a zone-free wall-clock value and is wrong for timestamps.
  • Store and exchange Instant (or ISO-8601 with offset); convert to ZonedDateTime at the edge where a person reads it.
  • Duration is exact elapsed time; Period is calendar distance — they disagree across DST and month ends, by design.
  • All java.time types are immutable and thread-safe; keep DateTimeFormatter instances static, pass a Locale, and prefer uuuu with strict resolution when validating input.
  • Convert legacy Date, epoch millis and JDBC values at the boundary and inject a Clock so time-based code is testable.

Sources and further reading

Frequently asked questions

Should I use Optional as a field or method parameter?
No. Optional was designed as a return type for methods that may legitimately have no result. As a field it is not serializable, adds an allocation, and still needs a null check because the Optional reference itself could be null. As a parameter it forces callers to wrap values; an overload or a nullable parameter with @Nullable documentation is clearer.
Which java.time type should I store a timestamp in?
Instant. It is a point on the UTC timeline with no zone ambiguity and maps directly to TIMESTAMP WITH TIME ZONE in PostgreSQL or to epoch milliseconds. Convert to ZonedDateTime only at the edge where a human reads it. LocalDateTime is wrong for timestamps because it cannot say which moment it refers to.
What is the difference between Duration and Period?
Duration is an exact amount of time in seconds and nanoseconds — 90 minutes is always 5,400 seconds. Period is a calendar amount in years, months and days — one month is 28 to 31 days and one day can be 23 or 25 hours across a DST change. Use Duration for time-based arithmetic and Period for date-based arithmetic.
Is DateTimeFormatter thread-safe?
Yes. Unlike the old SimpleDateFormat, which corrupts output when shared between threads, DateTimeFormatter is immutable and safe to keep in a static final field. Create it once with a pattern or use the predefined ISO constants.