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
ofandparse - Adding, subtracting and comparing dates
- Measuring gaps with
ChronoUnit,PeriodandDuration - 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
LocalDateis a date with no time and no time zone, such as a birthday or an exam date. Create one withLocalDate.of(2026, 1, 15)or parse ISO text like"2026-06-10". Months are numbered 1 to 12, unlike the old API.- All
java.timeobjects are immutable.plusMonths(3)returns a new date and leavesadmissionunchanged, so always use the returned value. ChronoUnit.DAYS.betweencounts the total days (146).Period.betweensplits the gap into years, months and days (4 months 26 days).isBefore,isAfterandisLeapYearanswer common questions directly.getDayOfWeek()returns aDayOfWeekenum.LocalTimeholds a time of day andLocalDateTimecombines 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.ofPatterndescribes a layout:ddday,MMmonth,yyyyyear,hh12-hour clock,HH24-hour clock,mmminutes,aAM/PM,EEEEfull day name andMMMMfull month name. The same pattern parses text such as"05-08-2026".- Passing
Locale.ENGLISHfixes the language of day and month names; otherwise they follow the computer’s settings. atZoneattaches a time zone to a local date-time.withZoneSameInstantshows the same moment in another zone: 3 pm in Dhaka (UTC+6) is 9 am in London on that date.- An
Instantis a point on the global timeline in UTC, ideal for logs and timestamps.Durationmeasures time in hours, minutes and seconds;PT2H45M30Sis its ISO format. - Impossible dates such as 30 February throw
DateTimeParseExceptioninstead of silently rolling over.
Which Class to Use
| Class | Holds | Example use |
|---|---|---|
LocalDate | Date only | Birthday, due date |
LocalTime | Time of day | Shop opening hour |
LocalDateTime | Date and time, no zone | A class timetable entry |
ZonedDateTime | Date, time and time zone | An online meeting across countries |
Instant | Moment in UTC | Log timestamps, database audit columns |
Period | Years, months, days | Age, subscription length |
Duration | Hours, minutes, seconds | How 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
- Ignoring the return value of
plusDaysand similar methods, expecting the original object to change. - Using
mmfor months.mmis minutes; months areMM. - Using
LocalDateTimefor events in different time zones. Store anInstantorZonedDateTimeinstead. - Using the old
java.util.DateandSimpleDateFormatin 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.timeclasses; they are immutable and clear. LocalDate,LocalTimeandLocalDateTimehave no time zone;ZonedDateTimeandInstantdo.- Measure gaps with
ChronoUnit,PeriodorDuration. - Format and parse with
DateTimeFormatterpatterns.
