java.time (Date and Time API)

Master Java's modern date-time API: LocalDate, LocalDateTime, Instant, Duration, Period, and ZonedDateTime for robust time handling.

published: reading time: 20 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Master Java's modern date-time API: LocalDate, LocalDateTime, Instant, Duration, Period, and ZonedDateTime for robust time handling.

java.time (Date and Time API)

Introduction

Java 8 introduced the java.time package to address the well-known deficiencies of java.util.Date and java.util.Calendar. The new API is immutable, thread-safe, and follows a clear domain-driven design with separate types for different time concepts.

When to Use

Use Case Recommended Type
Birthdays, holidays, birthdays LocalDate
Absolute point in time Instant
Precise elapsed durations Duration
Age calculation, calendar periods Period
Time with timezone awareness ZonedDateTime / OffsetDateTime
Human-readable date and time LocalDateTime

When NOT to Use

  • Legacy interop: Use java.util.Date only when forced by legacy APIs.
  • Database columns: SQL TIMESTAMP WITH TIME ZONE mappings depend on the database and JDBC driver. Check the driver documentation; LocalDateTime has no zone or offset and does not identify an instant.
  • Serializing to JSON: Configure ObjectMapper with JavaTimeModule instead of manual parsing.

Core Types Diagram

classDiagram
    class Temporal~T~ {
        <<interface>>
    }
    class TemporalAmount {
        <<interface>>
    }
    class LocalDate {
        +now() LocalDate
        +of(int year, int month, int day) LocalDate
        +plusDays(long) LocalDate
        +minusDays(long) LocalDate
        +isAfter(LocalDate) boolean
    }
    class LocalDateTime {
        +now() LocalDateTime
        +of(int year, int month, int day, int hour, int min) LocalDateTime
        +toLocalDate() LocalDate
        +toLocalTime() LocalTime
    }
    class Instant {
        +now() Instant
        +ofEpochSecond(long) Instant
        +plus(Duration) Instant
        +minus(Duration) Instant
        +toEpochMilli() long
    }
    class ZonedDateTime {
        +now(ZoneId) ZonedDateTime
        +of(LocalDateTime, ZoneId) ZonedDateTime
        +withZoneSameInstant(ZoneId) ZonedDateTime
    }
    class Duration {
        +ofDays(long) Duration
        +ofHours(long) Duration
        +between(Temporal, Temporal) Duration
        +toMillis() long
    }
    class Period {
        +ofDays(int) Period
        +ofMonths(int) Period
        +between(LocalDate, LocalDate) Period
        +getDays() int
    }

    Temporal~T~ <|-- LocalDate
    Temporal~T~ <|-- LocalDateTime
    Temporal~T~ <|-- Instant
    Temporal~T~ <|-- ZonedDateTime
    TemporalAmount <|-- Duration
    TemporalAmount <|-- Period
    LocalDateTime --> LocalDate : toLocalDate()
    ZonedDateTime --> LocalDateTime : composes

Code Examples

LocalDate — Birthdays and Calendar Dates

LocalDate is a calendar date with year, month, and day only. Pick it for birthdays, expiration dates, billing cycles, hire dates, or any date where the wall-clock time is irrelevant. It stores no time, timezone, or instant information — it is the lightest date type in java.time and the right default for business-domain date fields.

The API uses a fluent builder pattern. LocalDate.of(year, month, day) builds a specific date. now() reads the current date from the system clock in the default timezone. Arithmetic methods like plusDays(), minusMonths(), and plusYears() return new LocalDate instances rather than mutating the original — all java.time types are immutable. Comparison methods isAfter(), isBefore(), and isEqual() handle date ordering without requiring you to work with epoch days directly.

import java.time.LocalDate;
import java.time.Month;

LocalDate today = LocalDate.now();
LocalDate javaBirthday = LocalDate.of(1995, Month.MAY, 23);
LocalDate endOfYear = LocalDate.of(2026, 12, 31);

// Difference in days
long daysBetween = javaBirthday.until(today).getDays();
System.out.println("Java is " + daysBetween + " days old");

// Adding/subtracting
LocalDate nextWeek = today.plusWeeks(1);
LocalDate lastMonth = today.minusMonths(1);

// Comparison
if (today.isAfter(javaBirthday)) {
    System.out.println("Java has been around for a while");
}

Instant — Machine Timestamps

Instant is a point on the UTC timeline, with nanosecond precision since 1970-01-01T00:00:00Z. Unlike LocalDateTime, which has no zone or offset and does not identify an instant, an Instant refers to the same moment everywhere. It is the right type for machine timestamps, log event times, metric data points, and any time coordinate that must be consistent across distributed systems. When you need to correlate events across different machines or timezones, Instant is the answer.

The API stays minimal. Instant.now() captures the current moment. Instant.ofEpochSecond(long) and Instant.ofEpochMilli(long) reconstruct an instant from epoch values. Arithmetic uses Duration — instant.plus(Duration.ofMinutes(5)) or instant.minus(Duration.ofHours(1)). To display an Instant in a specific timezone, convert it to ZonedDateTime with atZone(ZoneId). For storage and transmission, toEpochMilli() serializes an instant to a long that any database or message queue can store.

import java.time.Instant;
import java.time.Duration;

Instant startup = Instant.now();
// ... app runs ...
Instant now = Instant.now();

Duration elapsed = Duration.between(startup, now);
System.out.println("Elapsed: " + elapsed.toMillis() + "ms");

// Convert to/from epoch millis
long epochMillis = Instant.now().toEpochMilli();
Instant restored = Instant.ofEpochMilli(epochMillis);

ZonedDateTime — Local Time, Zone Rules, and Instants

ZonedDateTime combines a LocalDateTime with a regional ZoneId and resolves it to an offset on the timeline. A ZoneId such as "Europe/Paris" carries the rules for daylight-saving changes. LocalDateTime alone has neither a zone nor an offset, so it cannot identify a unique instant (LocalDateTime API, ZonedDateTime API).

For a future event promised at a local wall-clock time, keep the LocalDateTime and ZoneId together, then define what to do at daylight-saving transitions. A local time can have no valid offsets during a spring gap, one on an ordinary day, or two during a fall overlap. ZoneRules.getValidOffsets() reports those cases (ZoneRules API). The example below rejects a gap and chooses the earlier offset during an overlap. ZonedDateTime.of(local, zone) has different defaults: it shifts a gap forward and uses the earlier offset in an overlap.

import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;

public class ScheduleResolutionDemo {
    static ZonedDateTime resolve(LocalDateTime local, ZoneId zone) {
        List<ZoneOffset> offsets = zone.getRules().getValidOffsets(local);
        if (offsets.isEmpty()) {
            throw new DateTimeException("Scheduled time falls in a daylight-saving gap: " + local);
        }

        // One offset is normal; index 0 is the earlier choice during an overlap.
        return ZonedDateTime.ofLocal(local, zone, offsets.get(0));
    }

    public static void main(String[] args) {
        ZoneId paris = ZoneId.of("Europe/Paris");
        LocalDateTime overlap = LocalDateTime.of(2026, 10, 25, 2, 30);
        System.out.println(resolve(overlap, paris));

        try {
            resolve(LocalDateTime.of(2026, 3, 29, 2, 30), paris);
        } catch (DateTimeException e) {
            System.out.println("Rejected the daylight-saving gap");
        }
    }
}

This example uses java.time, available since Java 8. With the installed time-zone rules for 2026, it prints a value in the earlier Paris offset and rejects the spring gap:

2026-10-25T02:30+02:00[Europe/Paris]
Rejected the daylight-saving gap

Use Instant for an already-fixed moment. For a schedule that must follow a region’s wall clock, retain the local date-time and zone so each occurrence can be resolved under an explicit gap/overlap policy.

Duration and Period — Elapsed Time

Duration and Period both express elapsed time, but they measure it in different units and serve different purposes. Duration models elapsed time as seconds and nanoseconds — use it when you need precise mechanical measurement: how long did this operation take, what is the latency between these two events, how many seconds until timeout. Duration is the right choice for performance measurement, animation timing, and any scenario where wall-clock accuracy in seconds or nanoseconds is what you need.

Period models elapsed time as calendar units — days, months, years. Use it when you are doing calendar arithmetic: how old is this person, what date is three months from now, does this subscription renew on the same day next month. Period knows that a month has a different number of days and that adding one month to January 31 lands in February. When the question is “when” rather than “how long,” Period is the right choice. Near DST transitions, a Period of one day may represent 23 or 25 hours of wall-clock time, whereas a Duration of one day is always exactly 86,400 seconds.

import java.time.Duration;
import java.time.Period;
import java.time.LocalDate;

Duration oneHour = Duration.ofHours(1);
Duration halfHour = Duration.ofMinutes(30);

// Combine durations
Duration total = oneHour.plus(halfHour); // 90 minutes

// Period for calendar math
LocalDate start = LocalDate.of(2026, 1, 1);
LocalDate end = LocalDate.of(2026, 5, 23);
Period age = Period.between(start, end);
System.out.println("Months: " + age.getMonths() + ", Days: " + age.getDays());

Date Formatting and Parsing

DateTimeFormatter is the formatting workhorse of java.time. Unlike SimpleDateFormat, every DateTimeFormatter is immutable and thread-safe. You set the pattern and Locale at construction, and that is final.

The API breaks down into three practical layers. Static pre-defined formatters (ISO_LOCAL_DATE, ISO_LOCAL_TIME, ISO_LOCAL_DATE_TIME) handle machine-readable formats with no setup. Call ofPattern(String pattern) to build custom layouts from pattern symbols (yyyy for year, MM for month, dd for day, HH for hour, mm for minute). Then ofLocalizedDateTime(FormatStyle) layers in locale-aware formatting. FormatStyle.MEDIUM gives “Jan 23, 2026” in US English but “23 Jan 2026” in UK English.

Parsing works similarly. parse(CharSequence) alone assumes ISO_LOCAL_DATE_TIME. For anything else, pass the formatter: LocalDateTime.parse("23/05/2026 14:30", custom). Malformed input throws DateTimeParseException — guard untrusted input with try-catch. For user-facing fields that may arrive in flexible formats, add withResolverStyle(ResolverStyle.LENIENT) so “January 1, 2026” parses correctly even when the pattern expects “01/01/2026”.

import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;

DateTimeFormatter iso = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
DateTimeFormatter custom = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");

LocalDateTime now = LocalDateTime.now();
String formatted = now.format(custom);
System.out.println(formatted); // e.g., 23/05/2026 14:30

LocalDateTime parsed = LocalDateTime.parse("23/05/2026 14:30", custom);

Failure Scenarios

Scenario Problem Solution
LocalDate.of(2026, 2, 30) DateTimeException — invalid day for February Validate day range: day > 0 && day <= month.length(year % 4 == 0)
Instant.parse("2026-02-30T10:00") DateTimeParseException Always parse through a formatter with lenient mode if input is untrusted
Duration.between(date1, date2) java.time.temporal.UnsupportedTemporalTypeException Duration works with Instant, LocalDateTime, OffsetTime; use Period for LocalDate
ZonedDateTime.now(ZoneId.of("Mars")) ZoneRulesException Validate zone ID against ZoneId.getAvailableZoneIds()
Local schedule during DST gap/overlap A wall-clock time can be missing or occur twice Choose and document a gap/overlap policy before resolving it
Race condition on cached ZoneId Stale zone data Do not cache ZoneId instances across JVM restarts

Trade-off Table

Aspect java.time java.util.Date java.util.Calendar
Thread safety Immutable, thread-safe Mutable, not thread-safe Mutable, not thread-safe
API clarity Domain-specific types Single ambiguous type Complex, inconsistent
Timezone handling First-class ZoneId Manual offset management Partial support
Performance Slight overhead for immutability Fast but unsafe Slow and unsafe
New features Streams, parsing, formatting Legacy only Legacy only

Observability Checklist

// Instrumenting time operations for observability
import java.time.Instant;
import java.time.Duration;

public class TimedOperation {
    private final Instant start;

    public TimedOperation() {
        this.start = Instant.now();
    }

    public long elapsedMillis() {
        return Duration.between(start, Instant.now()).toMillis();
    }

    // Log with structured fields for observability platforms
    public void logDuration(String operation) {
        System.out.println("operation=" + operation +
            " duration_ms=" + elapsedMillis() +
            " timestamp=" + Instant.now());
    }
}
  • Measure elapsed time with Duration.between(start, end) and expose as a metric.
  • Use Instant for log timestamps rather than System.currentTimeMillis().
  • Validate timezone IDs at startup to fail fast on misconfiguration.
  • Store Instant in persistence layers, not LocalDateTime, to preserve the moment in time.
  • Log parsing failures with the raw input string for debugging.

Security Notes

  • Time-of-check to time-of-use (TOCTOU): Immutable types eliminate some TOCTOU races but calendar operations still require atomic validation.
  • Timezone spoofing: If user input sets the timezone, validate it against an allowlist of permitted zones.
  • Deserialization attacks: Malformed date strings in untrusted input can cause DateTimeParseException; catch and log securely without leaking stack traces.
  • Leap second handling: Instant treats leap seconds as a 1-second increment, not as a special case — do not rely on Instant for financial time calculations.

Pitfalls

  1. Confusing Duration with Period: Duration.ofDays(1) creates a 24-hour duration, while Period.ofDays(1) represents a calendar day which may have different length near DST transitions.
  2. Modeling a regional schedule with LocalDateTime alone: Keep the wall-clock value with a ZoneId, then define the DST gap/overlap policy before resolving it.
  3. Immutability surprises: Methods like plusDays() return a new instance — the original is unchanged. Assign the result.
  4. Epoch overflow: Instant.MAX is year +1,000,000,000; Instant.MIN is year -1,000,000,000. Unlikely to hit, but be aware.
  5. Resolving scheduled local times: A daylight-saving gap has no valid offset; ZonedDateTime.of(local, zone) shifts it forward by the gap length. An overlap has two offsets, and the default is the earlier one. Choose a policy that fits the schedule instead of relying on these defaults.

Quick Recap

  • java.time is immutable, thread-safe, and domain-driven.
  • LocalDate for calendar dates, LocalDateTime for naive datetime, Instant for UTC timestamps.
  • Pair LocalDateTime with ZoneId for a future wall-clock schedule, and define a DST gap/overlap policy. Use ZonedDateTime after resolving it.
  • Duration for precise elapsed time, Period for calendar-based elapsed time.
  • Format with DateTimeFormatter; parse with LocalDateTime.parse(str, formatter).
  • Always use Instant for logging and metric timestamps.
  • Prefer Duration.between() over manual subtraction for elapsed time.

Interview Questions

1. What is the difference between `Instant` and `LocalDateTime`?
`Instant` identifies one point on the UTC timeline. `LocalDateTime` is a wall-clock date and time with no zone or offset, so it does not identify a unique instant; the same local value can map to different instants in different zones. Use `Instant` for fixed moments and keep `LocalDateTime` with a `ZoneId` for a future regional schedule."

2. How does `Duration` differ from `Period`?
`Duration` models a precise amount of time in seconds or nanoseconds — it is suited for measuring elapsed time between two `Instant` values. `Period` models a calendar-based amount in days, months, and years — it is suited for date arithmetic where you want "1 month later" to roll over to the next month calendar-wise. A `Duration` of one day is always exactly 86,400 seconds; a `Period` of one day may represent a different amount of wall-clock time near DST transitions."

3. What happens when you parse an invalid date like `2026-02-30`?
A `DateTimeParseException` is thrown at runtime. The `java.time` types perform strict validation — there is no silent rollover or clamping like the legacy `Calendar`. You must validate input before parsing or catch the exception explicitly."

4. How do you convert between time zones in `java.time`?
Use `ZonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Tokyo"))` to convert a `ZonedDateTime` to a different zone while preserving the same instant in time. Use `ZonedDateTime.withZoneSameLocal()` if you want to keep the local time but change the zone (this can produce different instants near DST transitions). For `Instant`, use `Instant.atZone(ZoneId)` to attach a zone."

5. Why is `java.util.Date` considered legacy and when might you still need it?
`java.util.Date` is mutable and not thread-safe, its `toString()` returns a misleading local timezone string, and month numbering is 0-based. You still need it only for interoperability with legacy APIs that require `java.util.Date` — JDBC `setTimestamp()`, some enterprise integrations, and `java.util.concurrent.ScheduledExecutorService`. In all new code, use `java.time`."

6. What is the difference between `ZonedDateTime` and `OffsetDateTime`?
`ZonedDateTime` has a regional `ZoneId` with daylight-saving rules; `OffsetDateTime` has a fixed UTC offset. For a future wall-clock schedule, keep the `LocalDateTime` and `ZoneId` together and define how to handle gaps and overlaps before resolving an occurrence. Use `Instant` when the moment is already fixed."

7. How does `Instant.now()` behave across different JVMs and how should you correlate instants?
`Instant.now()` uses the system clock in UTC — it returns the same instant value across all JVMs on the same machine if they share the same clock source. However, different machines may have slightly different clock readings. For distributed system correlation, use a centralized time source (NTP) or log both wall-clock time and epoch millis. Never assume two JVMs have synchronized clocks — always use epoch-based timestamps (`Instant.toEpochMilli()`) for cross-system correlation."

8. What is the purpose of `TemporalAdjusters` and when should you use them?
`TemporalAdjusters` provides common date adjustments: `nextOrSame(DayOfWeek)`, `lastDayOfMonth()`, `firstDayOfNextMonth()`, etc. They implement the `TemporalAdjuster` interface and can be passed to `with()` methods on date-time types. For example: `date.with(TemporalAdjusters.lastDayOfMonth())` returns the last day of the month. Use these instead of manual day-of-month calculations for readability and correctness near month boundaries."

9. What happens when you add months to a date near the end of the month?
`LocalDate.of(2026, 1, 31).plusMonths(1)` throws `DateTimeException` because February has no 31st day. The design intentionally prevents silent rollover. Options: use `plusDays()` for a fixed day count, use `withDayOfMonth()` after adding months to clamp to the valid day, or check the day range beforehand and decide whether to throw or clamp. The same rule applies to `minusMonths()`, `plusYears()`, etc."

10. What is the difference between `Duration` and `Period` when measuring elapsed time across DST transitions?
A `Duration` of one day is always exactly 86,400 seconds (24 hours). A `Period` of one day represents a calendar day — near DST transitions, a day may have 23 or 25 hours. For example, adding a `Period` of one day across a spring-forward DST transition produces a different wall-clock result than adding a `Duration` of one day. Use `Period` for human-calendar arithmetic; use `Duration` for precise elapsed time measurement."

11. What does `ZoneId.of("UTC")` return and how does it differ from `ZoneOffset.UTC`?
`ZoneId.of("UTC")` returns the "UTC" zone ID (a `ZoneId` with fixed offset of 0). `ZoneOffset.UTC` is a `ZoneOffset` representing UTC with zero offset. Both represent UTC but have different types — `ZoneOffset` is a simple fixed offset, while `ZoneId` is a full timezone with rules. When you need UTC specifically, `ZoneOffset.UTC` is cleaner; when you need a full `ZoneId` for methods requiring a zone, use `ZoneId.of("UTC")`."

12. How does `LocalDateTime.parse()` handle invalid dates and what should you use instead?
`LocalDateTime.parse(CharSequence)` uses `DateTimeFormatter.ISO_LOCAL_DATE_TIME` by default. If the input string is malformed, it throws `DateTimeParseException`. For untrusted input, wrap parsing in a try-catch or use `DateTimeFormatter` with a custom pattern and `setResolverStyle(ResolverStyle.STRICT)` for stricter validation. For user-facing input that may be flexible, use `DateTimeFormatter` with `ResolverStyle.SMART` or `LENIENT` as appropriate."

13. What is the purpose of `Instant` in logging and metric systems?
`Instant` identifies a point on the UTC timeline and fits log timestamps and metric events. `Instant.now()` reads the system clock but is not guaranteed to be monotonic; use [`System.nanoTime()`](https://docs.oracle.com/en/java/javase/27/docs/api/java.base/java/lang/System.html) to measure elapsed time. `LocalDateTime` has no zone or offset, so resolving it to an instant requires a `ZoneId` and a policy for gaps or overlaps. Use `Instant` when the moment is fixed; keep a local date-time with its zone for a future regional schedule."

14. What does `Period.between()` return and how does it differ from `Duration.between()`?
`Period.between(LocalDate start, LocalDate end)` returns a `Period` with years, months, and days — appropriate for calendar arithmetic. `Duration.between(Instant start, Instant end)` returns a `Duration` with seconds and nanoseconds — appropriate for precise elapsed time. If you call `Duration.between()` on two `LocalDate` values, it throws an exception because `LocalDate` is not a `Temporal` type that `Duration.between()` accepts."

15. What is the behavior of `ZonedDateTime` during the hour before or after DST transition?
`ZoneRules.getValidOffsets(local)` returns no offsets for a gap, one normally, and two during an overlap. `ZonedDateTime.of(local, zone)` shifts a gap forward and uses the earlier offset for an overlap. For a scheduled event, choose a policy explicitly; `ofLocal(local, zone, chosenOffset)` lets you select a valid overlap offset. This example rejects gaps and chooses the earlier overlap offset."

16. What is the difference between `DateTimeFormatter.ofLocalizedDateTime()` and the ISO formatters?
`DateTimeFormatter.ofLocalizedDateTime()` uses locale-specific formatting — for example, `FormatStyle.MEDIUM` produces "Jan 23, 2026" in US locale but "23 Jan 2026" in UK locale. The ISO formatters (`DateTimeFormatter.ISO_LOCAL_DATE_TIME`, etc.) always use the ISO format regardless of locale. Use localized formatters for displaying dates to users in their locale; use ISO formatters for machine-to-machine communication and storage."

17. What is the purpose of `Period.ofDays()`, `Period.ofMonths()`, and `Period.ofYears()` factory methods?
These create a `Period` with only the specified unit set — `Period.ofDays(5)` creates a period of 5 days with 0 months and 0 years. They are more explicit than `Period.of(5, 0, 0)` because they document intent immediately. Use them when you need a simple period of a single unit. `Period.parse("P5D")` parses ISO-8601 duration format and produces the same result."

18. How does `TemporalUnit.between()` differ from `Duration.between()` and `Period.between()`?
`TemporalUnit.between(Temporal start, Temporal end)` is the general-purpose method on the `TemporalUnit` interface (e.g., `ChronoUnit.DAYS.between(start, end)`) and can compute the difference between any two temporal types, returning the appropriate unit as a `long`. It handles the type conversion — for example, `ChronoUnit.DAYS.between(LocalDate.of(2026, 1, 1), LocalDate.of(2026, 1, 31))` returns 30. `Duration.between()` and `Period.between()` are specialized methods for specific temporal types."

19. What is the difference between `LocalDate.now(ZoneId)` and `ZonedDateTime.now(ZoneId).toLocalDate()`?
Both return the current date in the specified zone. LocalDate.now(ZoneId) is the cleaner API — it directly returns the date portion of the current instant in that zone. ZonedDateTime.now(ZoneId).toLocalDate() creates an intermediate ZonedDateTime object and then extracts the date from it. The result is identical, but LocalDate.now(ZoneId) is more efficient and readable."

20. What happens when you call `plusDays()` versus `plus(Duration.ofDays(1))` on an `Instant`?
instant.plusDays(1) does not exist on Instant — Instant only supports plus(long, TemporalUnit) or plus(Duration). instant.plus(Duration.ofDays(1)) works because Duration implements TemporalAmount. For Instant, use instant.plus(1, ChronoUnit.DAYS) or instant.plus(Duration.ofDays(1)). For LocalDate, plusDays(int) is the standard method. Mixing them can cause confusion — check the type before calling methods."

Further Reading

Conclusion

The java.time package addresses everything wrong with java.util.Date and java.util.Calendar — mutability, thread-safety issues, confusing API design, and zero-based month indexing. The new API is immutable by design, which makes it safe to share across threads and predictable across time-zone boundaries. Once you internalize the domain model (LocalDate for calendar days, Instant for machine timestamps, ZonedDateTime for scheduled events), you will find date-time code becomes significantly shorter and less bug-prone.

Choose the type that matches the value. LocalDate stores a calendar date with no time component, which fits birthdays and expiration dates. Instant identifies a fixed point on the UTC timeline, which fits logs and metrics. For a future event that must follow local time in a region, keep its LocalDateTime and ZoneId together and set a policy for daylight-saving gaps and overlaps before resolving it to a ZonedDateTime.

Duration vs Period is another critical distinction. Duration measures elapsed time in seconds and nanoseconds between two TemporalAccessor points — it is appropriate for measuring program execution time, latency metrics, and any time interval that is precisely defined. Period measures elapsed time in calendar units (days, months, years) between two LocalDate values — use it for age calculations, subscription periods, and any interval where calendar semantics matter more than precise milliseconds.

For formatting and parsing, use java.time.format.DateTimeFormatter with the patterns from java.time rather than the legacy java.text formatting classes. DateTimeFormatter is immutable and thread-safe, whereas SimpleDateFormat is neither. The pattern syntax is similar but the new API is more consistent and supports localization properly.

  • Use LocalDate for birthdays, holidays, and any date without a time component
  • Use Instant for all machine timestamps — log timestamps, metric events, and event sourcing
  • Keep LocalDateTime and ZoneId for a future regional schedule; define the DST gap/overlap policy before resolving to ZonedDateTime
  • Use Duration for precise elapsed time between instants; use Period for calendar-based intervals
  • Always use DateTimeFormatter from java.time.format — never SimpleDateFormat for new code
  • java.time types are immutable — methods like plusDays() return new instances, they do not mutate

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals