Reading history

Java Date and Time API (LocalDate, LocalDateTime, ZonedDateTime)

6 min read 0 views

Work with dates in Java using java.time: LocalDate and LocalDateTime, date arithmetic, Period and Duration, DateTimeFormatter patterns and time zone conversion.

Dates look simple until you need to add a month to 31 January, count the days to an exam, or show a meeting time in two countries. Java’s modern Date-Time API in the java.time package handles all of this correctly. It replaced the old, error-prone Date and Calendar classes in Java 8. This lesson covers the classes you will use most: LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Period, Duration and DateTimeFormatter.

In this lesson you will learn

  • Creating dates and times with of and parse
  • Adding, subtracting and comparing dates
  • Measuring gaps with ChronoUnit, Period and Duration
  • Formatting and parsing with DateTimeFormatter
  • Converting between time zones

You should know Java strings and loops.

Dates, Times and Date Arithmetic

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        LocalDate admission = LocalDate.of(2026, 1, 15);
        LocalDate exam = LocalDate.parse("2026-06-10");
        System.out.println(admission + " is a " + admission.getDayOfWeek());

        // Date arithmetic returns new objects; the original never changes
        LocalDate later = admission.plusMonths(3).plusDays(10);
        System.out.println("plus 3 months 10 days: " + later + ", original: " + admission);

        System.out.println("days until exam: " + ChronoUnit.DAYS.between(admission, exam));
        Period p = Period.between(admission, exam);
        System.out.println("period: " + p.getMonths() + " months " + p.getDays() + " days");

        System.out.println("2028 leap year? " + LocalDate.of(2028, 1, 1).isLeapYear());
        System.out.println("exam after admission? " + exam.isAfter(admission));

        // First Friday after the exam
        LocalDate d = exam.plusDays(1);
        while (d.getDayOfWeek() != DayOfWeek.FRIDAY) d = d.plusDays(1);
        System.out.println("first Friday after exam: " + d);

        LocalTime start = LocalTime.of(9, 30);
        LocalDateTime classAt = LocalDateTime.of(exam, start);
        System.out.println(classAt + " ends at " + start.plusMinutes(90));
    }
}

Output

2026-01-15 is a THURSDAY
plus 3 months 10 days: 2026-04-25, original: 2026-01-15
days until exam: 146
period: 4 months 26 days
2028 leap year? true
exam after admission? true
first Friday after exam: 2026-06-12
2026-06-10T09:30 ends at 11:00
  • LocalDate is a date with no time and no time zone, such as a birthday or an exam date. Create one with LocalDate.of(2026, 1, 15) or parse ISO text like "2026-06-10". Months are numbered 1 to 12, unlike the old API.
  • All java.time objects are immutable. plusMonths(3) returns a new date and leaves admission unchanged, so always use the returned value.
  • ChronoUnit.DAYS.between counts the total days (146). Period.between splits the gap into years, months and days (4 months 26 days).
  • isBefore, isAfter and isLeapYear answer common questions directly. getDayOfWeek() returns a DayOfWeek enum.
  • LocalTime holds a time of day and LocalDateTime combines a date and a time. A 90-minute class starting at 09:30 ends at 11:00.

Formatting, Time Zones and Durations

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        LocalDateTime meeting = LocalDateTime.of(2026, 3, 26, 15, 0);

        // Formatting and parsing with patterns
        DateTimeFormatter bd = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm a", Locale.ENGLISH);
        System.out.println(meeting.format(bd));
        System.out.println(meeting.format(DateTimeFormatter.ofPattern("EEEE, d MMMM yyyy", Locale.ENGLISH)));
        LocalDate parsed = LocalDate.parse("05-08-2026", DateTimeFormatter.ofPattern("dd-MM-yyyy"));
        System.out.println("parsed: " + parsed);

        // Time zones: the same instant in two cities
        ZonedDateTime dhaka = meeting.atZone(ZoneId.of("Asia/Dhaka"));
        ZonedDateTime london = dhaka.withZoneSameInstant(ZoneId.of("Europe/London"));
        System.out.println("Dhaka:  " + dhaka);
        System.out.println("London: " + london);

        // Durations between instants
        Instant a = Instant.parse("2026-03-26T09:00:00Z");
        Instant b = Instant.parse("2026-03-26T11:45:30Z");
        Duration dur = Duration.between(a, b);
        System.out.println(dur + " = " + dur.toMinutes() + " minutes");

        try {
            LocalDate.parse("2026-02-30");
        } catch (DateTimeParseException e) {
            System.out.println("Invalid date rejected: 2026-02-30");
        }
    }
}

Output

26/03/2026 03:00 PM
Thursday, 26 March 2026
parsed: 2026-08-05
Dhaka:  2026-03-26T15:00+06:00[Asia/Dhaka]
London: 2026-03-26T09:00Z[Europe/London]
PT2H45M30S = 165 minutes
Invalid date rejected: 2026-02-30
  • DateTimeFormatter.ofPattern describes a layout: dd day, MM month, yyyy year, hh 12-hour clock, HH 24-hour clock, mm minutes, a AM/PM, EEEE full day name and MMMM full month name. The same pattern parses text such as "05-08-2026".
  • Passing Locale.ENGLISH fixes the language of day and month names; otherwise they follow the computer’s settings.
  • atZone attaches a time zone to a local date-time. withZoneSameInstant shows the same moment in another zone: 3 pm in Dhaka (UTC+6) is 9 am in London on that date.
  • An Instant is a point on the global timeline in UTC, ideal for logs and timestamps. Duration measures time in hours, minutes and seconds; PT2H45M30S is its ISO format.
  • Impossible dates such as 30 February throw DateTimeParseException instead of silently rolling over.

Which Class to Use

ClassHoldsExample use
LocalDateDate onlyBirthday, due date
LocalTimeTime of dayShop opening hour
LocalDateTimeDate and time, no zoneA class timetable entry
ZonedDateTimeDate, time and time zoneAn online meeting across countries
InstantMoment in UTCLog timestamps, database audit columns
PeriodYears, months, daysAge, subscription length
DurationHours, minutes, secondsHow long a task took

For the current moment use LocalDate.now(), LocalDateTime.now() or Instant.now(). The examples above use fixed dates so their output never changes.

Common Mistakes

  1. Ignoring the return value of plusDays and similar methods, expecting the original object to change.
  2. Using mm for months. mm is minutes; months are MM.
  3. Using LocalDateTime for events in different time zones. Store an Instant or ZonedDateTime instead.
  4. Using the old java.util.Date and SimpleDateFormat in new code. They are mutable and not thread-safe.

Practice Exercises

Exercise 1. Calculate a person’s age in whole years on 16 November 2026 if they were born on 21 March 2004.

Show answer
int age = Period.between(LocalDate.of(2004, 3, 21), LocalDate.of(2026, 11, 16)).getYears();
System.out.println(age);   // 22

Exercise 2. What is LocalDate.of(2026, 1, 31).plusMonths(1)?

Show answer

2026-02-28. February 2026 has no 31st, so Java uses the last valid day of the month instead of overflowing into March.

Frequently Asked Questions

How do I convert an old java.util.Date to the new API?

Call date.toInstant() to get an Instant, then atZone(ZoneId.systemDefault()) to get a ZonedDateTime, from which you can take toLocalDate().

Which time zone ID should I use for Bangladesh?

ZoneId.of("Asia/Dhaka"). Use region IDs like this rather than fixed offsets, so daylight-saving rules are handled correctly in countries that use them.

Summary

  • Use java.time classes; they are immutable and clear.
  • LocalDate, LocalTime and LocalDateTime have no time zone; ZonedDateTime and Instant do.
  • Measure gaps with ChronoUnit, Period or Duration.
  • Format and parse with DateTimeFormatter patterns.

Next: Java Regular Expressions (Regex).

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *