Date and Time

Basic Java
≈ 3 min read

Time in a program is not one number

A birthday, a meeting time, the moment a request was sent, and “two hours from now” look similar, but they mean different things in code. Some values need only a calendar date, others need an exact point on the global timeline, and some also need the rules of a particular time zone. The java.time package separates these tasks into different types so that the meaning of a value is clear directly from the code.

In this section, we will build a complete model for working with time: from local dates and times to absolute timestamps, time zones, intervals, formatting, and the common Temporal API abstractions. At the end, we will separately look at older classes that still appear in existing projects.

What this section contains

  • LocalDate, LocalTime, and LocalDateTime. We will examine values without a time zone: a calendar date, a time of day, and their combination.
  • Instant and timestamps. We will learn to represent a specific point on the global timeline and work with epoch time.
  • ZoneId and ZonedDateTime. We will add time zones and see why a simple offset such as +03:00 is sometimes not enough.
  • Duration and Period. We will separate an exact duration on the timeline from a calendar-based amount in years, months, and days.
  • DateTimeFormatter. We will learn to turn dates and times into text and back without manually assembling strings.
  • Date and time arithmetic. We will look at addition, subtraction, comparison, and calculating the distance between values.
  • Temporal API. We will connect the familiar classes through common interfaces, units, fields, and ready-made date adjustments.
  • Legacy Date API. We will learn to read code that uses Date, Calendar, and SimpleDateFormat and move toward the modern API.

The order matters: first you need to understand what kind of time value each core class stores, and only then perform operations on it, format it, and generalize it through the Temporal API. That way, code such as “a meeting at 10:00 in Berlin” and “the request was sent at this instant” will not accidentally be stored in the same way.

LocalDate birthday = LocalDate.of(2000, 5, 12);
Instant sentAt = Instant.now();
ZonedDateTime meeting = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));

All three values are related to time, but they answer different questions. Learning to choose the right type will be the main foundation for the entire section.