AI Hints
Home›Java Tutorial›StringBuilder, Dates and Times, Packages and Imports
Java · Lesson 110 of 120

Dates and Times

Java.time.

⏱ 2 min read▶ Video at 2:20:29🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Dates are tricky. Months have different lengths, there are leap years, and time zones. Java's java dot time package handles all of that for you.

  • Dates are tricky
  • Leap years, time zones
  • java.time handles it

Working with dates

Local date dot of makes a date, the fourteenth of March, twenty twenty six. Plus days adds thirty days, and handles the month change for us. Get day of week gives the weekday. Chrono unit counts the days between two dates. Local time holds a time of day. A formatter shows a date the way we like. And parse reads a date from text. Run it. The due date is the thirteenth of April, a Monday. The meeting ends at quarter past ten. And Christmas is after the due date.

Main.javajava
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Main {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2026, 3, 14);
        LocalDate due = start.plusDays(30);
        System.out.println("Start " + start + ", due " + due);
        System.out.println("Due on a " + due.getDayOfWeek());
        System.out.println("Days between: " + ChronoUnit.DAYS.between(start, due));
        LocalTime meeting = LocalTime.of(9, 30).plusMinutes(45);
        System.out.println("Meeting ends at " + meeting);
        var fmt = DateTimeFormatter.ofPattern("d MMMM yyyy");
        System.out.println("Nicely: " + due.format(fmt));
        LocalDate parsed = LocalDate.parse("2026-12-25");
        System.out.println("Christmas is after due? " + parsed.isAfter(due));
    }
}
Output
Start 2026-03-14, due 2026-04-13
Due on a MONDAY
Days between: 30
Meeting ends at 10:15
Nicely: 13 April 2026
Christmas is after due? true

The main classes

Each class holds a different kind of time. They're all immutable, so methods like plus days return a new value.

ClassHoldsExample
LocalDatea date2026-04-13
LocalTimea time of day10:15
LocalDateTimeboth2026-04-13T10:15
Duration / Periodan amount of timePT45M, P30D

Summary

Java dot time has local date, local time, and more. They're immutable, and handle months, and leap years, correctly. Next, organising code into packages.

Key takeaways
  • LocalDate.of
  • plusDays
  • DateTimeFormatter
Next up: Packages and Imports — organise your code