JAVA-230 · Lesson 6 of 12 · 21 min

Dates and times with java.time

▶ Video coming soon A video version of this lesson is on the way.

Rental returns were the topic on Wednesday, October 20. ShopBook stored rental start and end dates as LocalDate, which worked, but Odile now wanted things the old code could not answer cleanly: how many rentals ran past their due date, how long each bike was out to the hour, and whether a return logged "at 2:30 in the morning" on the night the clocks changed was a mistake or a real time. "Dates look simple," Ingrid said, "until you count across a month end, a leap year or a daylight saving change." The java.time package, added in Java 8 and designed by the author of the Joda-Time library, gives every one of those situations its own type, and all of its types are immutable and thread-safe.

The main types

Choose the type by asking what the value means. A birthday or a due date is a date with no time and no place: LocalDate. A shop opening time is a time of day: LocalTime. A repair booked for 10:00 on a day is a LocalDateTime, still with no time zone, which is fine as long as everyone involved is in the same place. An exact moment on the world's timeline, such as when a payment was recorded, is an Instant, stored as seconds and nanoseconds since 1970 in UTC. And a moment as people in a place see it, with that place's time zone rules, is a ZonedDateTime.

The main java.time types
TypeHoldsExampleUse for
LocalDateyear, month, day2027-10-20due dates, rental days, reports by day
LocalTimehour, minute, second18:30opening hours, slot times
LocalDateTimedate and time, no zone2027-10-20T18:30a booking in one city
Instanta point on the UTC timeline2027-10-20T22:30:00Zlogs, timestamps, ordering events
ZonedDateTimedate, time and a zone with rules2027-10-20T18:30-04:00[America/Toronto]times people see on a clock
Durationan amount of seconds and nanosecondsPT26Hhow long a bike was out, to the minute
Periodyears, months and daysP1M3Dhow many days or months between dates
YearMonth, DayOfWeek, Monthparts of a date2027-10, WEDNESDAYmonthly reports, schedules
A horizontal timeline showing one Instant as a single point labeled in UTC, with two clock faces above it showing the same moment as local times in Eastern time and in UTC, and a LocalDate drawn as a whole day-long band underneath.
An Instant is one point on the timeline; a ZonedDateTime is that point as a clock in one place shows it; a LocalDate is a whole calendar day with no place attached.

Every type is created with static factory methods such as of and parse, never with new, and every change returns a new object: due.plusDays(1) leaves due unchanged. That is the opposite of the old java.util.Date and Calendar classes, which were mutable, counted months from zero and mixed dates with times. New code should not use them; convert at the edges with methods such as Date.toInstant() when an old library hands you one.

Creating, adjusting and comparing dates

Use fixed dates in programs that must give the same answer every time, such as tests and reports. LocalDate.now() reads the computer's clock, so its output changes daily; when code needs "today", pass in a Clock or a date so tests can control it, as JAVA-220 showed with fixed clocks.

Java Example · Main.java
import java.time.*;
import java.time.temporal.*;

public class Main {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2027, 1, 29);
        LocalDate due = start.plusDays(3);
        LocalDate monthLater = start.plusMonths(1);

        System.out.println("Start: " + start + " (" + start.getDayOfWeek() + ")");
        System.out.println("Due: " + due);
        System.out.println("One month after Jan 29: " + monthLater);
        System.out.println("2028 is a leap year: " + Year.isLeap(2028));
        System.out.println("One month after Jan 29, 2028: " + LocalDate.of(2028, 1, 29).plusMonths(1));

        LocalDate returned = LocalDate.of(2027, 2, 3);
        System.out.println("Returned late? " + returned.isAfter(due));
        System.out.println("Days late: " + ChronoUnit.DAYS.between(due, returned));
        System.out.println("Last day of the month: " + start.with(TemporalAdjusters.lastDayOfMonth()));
        System.out.println("Next Saturday: " + start.with(TemporalAdjusters.next(DayOfWeek.SATURDAY)));
        System.out.println("Unchanged start: " + start);
    }
}
Output
Start: 2027-01-29 (FRIDAY)
Due: 2027-02-01
One month after Jan 29: 2027-02-28
2028 is a leap year: true
One month after Jan 29, 2028: 2028-02-29
Returned late? true
Days late: 2
Last day of the month: 2027-01-31
Next Saturday: 2027-01-30
Unchanged start: 2027-01-29

What this code does

plusMonths clamps to the last valid day, so one month after January 29, 2027 is February 28, while in the 2028 leap year it is February 29. ChronoUnit.DAYS.between counts the two days by which the return missed its due date, and TemporalAdjusters finds the month's last day and the next Saturday. The final line shows that none of these calls changed start, because every java.time object is immutable.

Period and Duration

There are two kinds of amount. A Period is measured in calendar units, years, months and days, and its length in hours depends on which dates it lies between; a month can be 28 to 31 days. A Duration is an exact amount of time in seconds and nanoseconds, the right type for "the bike was out 26 hours". Period.between(date1, date2) gives years, months and days; Duration.between(time1, time2) gives an exact duration and needs types that have a time. For a simple count in one unit, ChronoUnit.DAYS.between or ChronoUnit.HOURS.between is often the clearest choice.

Java Example · Main.java
import java.time.*;
import java.time.temporal.*;

public class Main {
    public static void main(String[] args) {
        LocalDate joined = LocalDate.of(2023, 6, 10);
        LocalDate report = LocalDate.of(2027, 10, 20);
        Period volunteer = Period.between(joined, report);
        System.out.println("Volunteering for: " + volunteer.getYears() + " years, "
                + volunteer.getMonths() + " months, " + volunteer.getDays() + " days (" + volunteer + ")");

        LocalDateTime out = LocalDateTime.of(2027, 10, 18, 16, 45);
        LocalDateTime back = LocalDateTime.of(2027, 10, 19, 18, 50);
        Duration rented = Duration.between(out, back);
        System.out.println("Out for: " + rented + " = " + rented.toHours() + " h " + rented.toMinutesPart() + " min");
        System.out.println("Whole days charged: " + (rented.toMinutes() + 24 * 60 - 1) / (24 * 60));

        System.out.println("Hours between: " + ChronoUnit.HOURS.between(out, back));
        System.out.println("A 90-minute repair: " + Duration.ofMinutes(90));
    }
}
Output
Volunteering for: 4 years, 4 months, 10 days (P4Y4M10D)
Out for: PT26H5M = 26 h 5 min
Whole days charged: 2
Hours between: 26
A 90-minute repair: PT1H30M

What this code does

Period.between reports Hamza's volunteering as 4 years, 4 months and 10 days, and its text form P4Y4M10D is the ISO 8601 notation. Duration.between gives the exact time the bike was out, 26 hours and 5 minutes, written PT26H5M, and the next line rounds up to whole days using integer arithmetic. Duration.ofMinutes(90) prints as PT1H30M, showing that durations are stored as one amount of time, not as separate fields.

Time zones and daylight saving time

A ZonedDateTime combines a LocalDateTime with a ZoneId such as America/New_York, and the zone's rules say how far that place is from UTC at any moment. Use region IDs like these, never fixed offsets like -05:00, because the offset changes twice a year. In 2027, clocks in Columbus spring forward at 2:00 a.m. on Sunday, March 14, and fall back at 2:00 a.m. on Sunday, November 7. On the spring date the times from 2:00 to 2:59 do not exist; on the fall date the times from 1:00 to 1:59 happen twice. java.time handles both: a time in the gap is moved forward by the length of the gap, and a time in the overlap uses the earlier offset unless you ask for the later one.

Two clock strips for the spring and fall changes in 2027. In March the strip jumps from 1:59 straight to 3:00, leaving a gap marked as times that do not exist. In November the strip runs 1:00 to 1:59 twice, once marked as daylight time and once as standard time.
At the spring change an hour of local times is skipped; at the fall change an hour of local times happens twice.
Java Example
import java.time.*;

public class Main {
    public static void main(String[] args) {
        ZoneId shop = ZoneId.of("America/New_York");

        ZonedDateTime gap = ZonedDateTime.of(LocalDateTime.of(2027, 3, 14, 2, 30), shop);
        System.out.println("2:30 on March 14 becomes " + gap);

        ZonedDateTime overlap = ZonedDateTime.of(LocalDateTime.of(2027, 11, 7, 1, 30), shop);
        System.out.println("1:30 on November 7 (first): " + overlap);
        System.out.println("1:30 on November 7 (second): " + overlap.withLaterOffsetAtOverlap());

        ZonedDateTime satEvening = ZonedDateTime.of(LocalDateTime.of(2027, 11, 6, 18, 0), shop);
        ZonedDateTime sunEvening = ZonedDateTime.of(LocalDateTime.of(2027, 11, 7, 18, 0), shop);
        System.out.println("Saturday 18:00 to Sunday 18:00: " + Duration.between(satEvening, sunEvening).toHours() + " hours");

        Instant paid = Instant.parse("2027-10-20T22:30:00Z");
        System.out.println("Payment at " + paid + " is " + paid.atZone(shop).toLocalTime() + " in the shop");
        System.out.println("Same moment in UTC: " + paid.atZone(ZoneOffset.UTC).toLocalTime());
    }
}
Output
2:30 on March 14 becomes 2027-03-14T03:30-04:00[America/New_York]
1:30 on November 7 (first): 2027-11-07T01:30-04:00[America/New_York]
1:30 on November 7 (second): 2027-11-07T01:30-05:00[America/New_York]
Saturday 18:00 to Sunday 18:00: 25 hours
Payment at 2027-10-20T22:30:00Z is 18:30 in the shop
Same moment in UTC: 22:30

What this code does

A local time of 2:30 on March 14 falls in the spring gap, so java.time moves it to 3:30 daylight time, which answers Odile's question: a return logged at 2:30 that night cannot be a real clock reading. On November 7, 1:30 happens twice, first at offset -04:00 and then at -05:00, and withLaterOffsetAtOverlap picks the second. The day from Saturday evening to Sunday evening is 25 hours long because the clocks fell back, which an exact Duration counts correctly and a simple count of days would not.

The rule for storing times follows from this. Record moments as Instant, in UTC, and convert to a ZonedDateTime only to show them to people. Store calendar facts that are not moments, such as a rental's due date, as LocalDate. Avoid storing LocalDateTime for events unless the zone is fixed and known, because without a zone a LocalDateTime cannot be placed on the timeline.

Formatting and parsing

toString on every java.time type gives the ISO 8601 form, such as 2027-10-20 and 2027-10-20T18:30, which is ideal for files and logs because it sorts correctly as text. For people, use a DateTimeFormatter. DateTimeFormatter.ofPattern("EEE MMM d, yyyy") builds one from pattern letters, and passing a Locale fixes the language of day and month names so the output does not change with the computer's settings. ofLocalizedDate(FormatStyle.MEDIUM) uses each locale's own customary style. Parsing uses the same formatters in reverse and throws DateTimeParseException when text does not match.

Common DateTimeFormatter pattern letters
LettersMeaningExample
yyyyyear2027
MM / MMM / MMMMmonth as number, short name, full name10 / Oct / October
d / ddday of month7 / 07
EEE / EEEEday of week, short / fullWed / Wednesday
HH / hhour, 24-hour / 12-hour18 / 6
mmminute30
aAM or PMPM
VV / zzone ID / zone nameAmerica/Toronto / EDT
Java Example · Main.java
import java.time.*;
import java.time.format.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        LocalDateTime pickup = LocalDateTime.of(2027, 10, 23, 10, 15);
        DateTimeFormatter label = DateTimeFormatter.ofPattern("EEE MMM d, yyyy 'at' h:mm a", Locale.ENGLISH);
        DateTimeFormatter csv = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        System.out.println("Ticket label: " + pickup.format(label));
        System.out.println("CSV field: " + pickup.format(csv));
        System.out.println("French Canadian: " + pickup.toLocalDate().format(
                DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(Locale.CANADA_FRENCH)));

        DateTimeFormatter typed = DateTimeFormatter.ofPattern("d/M/yyyy");
        LocalDate parsed = LocalDate.parse("7/11/2027", typed);
        System.out.println("Parsed 7/11/2027 as " + parsed + " (" + parsed.getMonth() + ")");

        try {
            LocalDate.parse("2027-02-30");
        } catch (DateTimeParseException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }
}
Output
Ticket label: Sat Oct 23, 2027 at 10:15 AM
CSV field: 2027-10-23T10:15:00
French Canadian: 23 octobre 2027
Parsed 7/11/2027 as 2027-11-07 (NOVEMBER)
Rejected: Text '2027-02-30' could not be parsed: Invalid date 'FEBRUARY 30'

What this code does

The label pattern quotes the word at and passes Locale.ENGLISH, so the output is the same on any computer, while ISO_LOCAL_DATE_TIME gives the sortable form for files. Parsing 7/11/2027 with a day-first pattern gives November 7, a reminder that slash dates are ambiguous and the pattern must match how the data was written. February 30 does not exist, so parsing it throws DateTimeParseException rather than quietly producing a wrong date.

Odile's three questions had three tidy answers by the end of the evening: rentals past due counted with isAfter on LocalDate, hours out measured with Duration on ZonedDateTime, and the 2:30 return flagged as impossible because it fell in the March gap. Hamza added one rule to the shop's code notes: "Never print now() in a report."

Try it yourself

Days late

Each rental has a due date and a return date. Use ChronoUnit.DAYS.between to work out how many days late each one is (0 if it came back on time or early) and print a line per bike.

The program should print CITY-1: 0, CARGO-1: 4 and TANDEM-1: 1.

import java.time.*;
import java.time.temporal.*;
import java.util.*;

public class Main {
    record Rental(String bike, LocalDate due, LocalDate returned) { }

    public static void main(String[] args) {
        List<Rental> rentals = List.of(
            new Rental("CITY-1", LocalDate.of(2027, 10, 4), LocalDate.of(2027, 10, 3)),
            new Rental("CARGO-1", LocalDate.of(2027, 9, 28), LocalDate.of(2027, 10, 2)),
            new Rental("TANDEM-1", LocalDate.of(2027, 10, 31), LocalDate.of(2027, 11, 1)));
        for (Rental r : rentals) {
            long late = 0;   // work this out
            System.out.println(r.bike() + ": " + late);
        }
    }
}

Try it yourself

A booking label

Format the booking time with a DateTimeFormatter pattern so the program prints Repair booked: Saturday, October 23 at 10:15 — full day name, full month name, day of month, then a 24-hour time.

Pass Locale.ENGLISH so the names are in English on any computer.

import java.time.*;
import java.time.format.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        LocalDateTime booked = LocalDateTime.of(2027, 10, 23, 10, 15);
        System.out.println("Repair booked: " + booked);
    }
}

Common mistakes

  • MistakePrinting LocalDate.now() in a report or test.

    InsteadUse fixed dates, or pass in a Clock or a date so results are repeatable.

  • MistakeStoring event times as LocalDateTime.

    InsteadStore moments as Instant and convert to ZonedDateTime for display.

  • MistakeUsing a fixed offset such as -05:00 for a city.

    InsteadUse a region ZoneId such as America/New_York, whose rules include daylight saving time.

  • MistakeAssuming every day has 24 hours.

    InsteadUse Duration between ZonedDateTime values; daylight saving days have 23 or 25 hours.

  • MistakeUsing java.util.Date and Calendar in new code.

    InsteadUse java.time and convert only at the edges of old libraries.

Summary and key terms

  • java.time gives each kind of date and time its own immutable type: LocalDate, LocalTime and LocalDateTime for calendar values with no zone, Instant for a point on the UTC timeline, and ZonedDateTime for a moment with a place's time zone rules.
  • Factory methods such as of and parse create them, and methods such as plusDays and with return new objects.
  • Period measures years, months and days, Duration measures exact time, and ChronoUnit.between counts one unit.
  • Region zone IDs handle daylight saving time: a local time in the spring gap is moved forward, a time in the fall overlap uses the earlier offset unless withLaterOffsetAtOverlap is called, and such days are 23 or 25 hours long. toString gives ISO 8601 text; DateTimeFormatter formats and parses other patterns, with a Locale for names, and invalid dates throw DateTimeParseException.
  • Store moments as Instant, and never print now() in reports or tests.
LocalDate
A date with no time of day and no time zone.
LocalDateTime
A date and time with no time zone, which cannot be placed on the timeline alone.
Instant
An exact point on the timeline, counted in UTC.
ZonedDateTime
A date and time together with a time zone and its rules.
ZoneId
An identifier for a time zone, such as America/New_York.
Duration
An exact amount of time in seconds and nanoseconds.
Period
An amount of time in years, months and days.
DateTimeFormatter
An object that formats dates and times as text and parses text back.
ISO 8601
The international standard for writing dates and times, such as 2027-10-20T18:30.
Daylight saving time gap
The hour of local times skipped when clocks spring forward.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Which type should hold a rental's due date?

    Show answer

    LocalDate.

  2. Which type should hold the moment a payment was recorded?

    Show answer

    Instant, shown to people as a ZonedDateTime.

  3. What is one month after January 29, 2027?

    Show answer

    February 28, 2027, because plusMonths clamps to the last valid day.

  4. How long is Saturday 18:00 to Sunday 18:00 on November 6 to 7, 2027, in the shop's time zone?

    Show answer

    25 hours, because the clocks fall back that night.

  5. Why pass a Locale to a DateTimeFormatter pattern?

    Show answer

    So day and month names are in a fixed language whatever the computer's settings.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz