Java Date and Time: LocalDate, LocalTime, LocalDateTime and ZonedDateTime (OCP 21)
The java.time types on the OCP Java 21 exam: picking LocalDate, LocalTime, LocalDateTime or ZonedDateTime, creating them with of() and now(), time zone offsets, plus/minus/with/at methods, end-of-month rules, immutability traps and DateTimeException.
kvi5hnuCode Sprout team member11 min readOn this page
Since Java 8, dates and times live in the java.time package (designed under JSR 310). It replaced the old java.util.Date, Calendar and SimpleDateFormat classes, which were mutable, not thread-safe and full of surprises such as months that started at 0. The old classes still exist for legacy code, but they aren't on the exam and new code shouldn't use them. To use the modern API, add one import:
import java.time.*;
This article covers the four main types and the methods that create and change them. Period, Duration, Instant and daylight saving time come in the next article.
Four types: how much information do you need?
Before writing any code, decide what the value has to carry:
| Type | Holds | Everyday example |
|---|---|---|
LocalDate | date only | a public holiday: it lasts the whole day, whatever the clock says |
LocalTime | time only | the time a shop opens, the same on every day |
LocalDateTime | date and time, no zone | "the fireworks start at 21 on 4 July", wherever you are |
ZonedDateTime | date, time and time zone | "the webinar starts at 9 New York time": one real moment |

Each type has a static now() method that reads the system clock (and, for ZonedDateTime, the system's default zone):
System.out.println(LocalDate.now()); // 2026-11-14
System.out.println(LocalTime.now()); // 16:02:47.318214
System.out.println(LocalDateTime.now()); // 2026-11-14T16:02:47.318297
System.out.println(ZonedDateTime.now()); // 2026-11-14T16:02:47.318641+05:30[Asia/Kolkata]
Your output depends on when and where you run it. What the exam cares about is the shape of each value:
- A date prints as
yyyy-MM-dd. - A time prints as
HH:mm, followed by seconds and a fraction only when they aren't zero. LocalDateTimejoins the two with a capitalT.ZonedDateTimeadds the offset from UTC and the zone ID in square brackets.
Java always uses a 24-hour clock in these toString results.
Time zones and offsets
UTC (Coordinated Universal Time) is the zero point. GMT (Greenwich Mean Time) uses the same zero for exam purposes. Every other zone is described by its offset from it: +05:30 means 5 hours 30 minutes ahead of UTC, and -04:00 means 4 hours behind. The same offset may appear as +02:00, GMT+2 or UTC+2.
To find out which of two zoned times happens first, convert both to UTC by subtracting the offset:
2026-06-20T06:50+05:30[Asia/Kolkata] 06:50 - 5:30 = 01:20 UTC
2026-06-20T07:50-04:00[America/New_York] 07:50 - (-4:00) = 11:50 UTC
The New York time is 10 hours 30 minutes after the Kolkata time, even though its clock reading is only one hour later. Subtracting a negative offset means adding. Some zones, such as India's, have a half-hour offset, and a few have a 45-minute one.
You get a zone with ZoneId.of(String). Prefer the region IDs in the Area/City form, such as "America/New_York" or "Europe/Paris". Older aliases like "US/Eastern" still work, but they're kept only for backward compatibility. Fixed offsets such as ZoneOffset.ofHours(2) are also valid zones, but they never change for daylight saving time.
Creating specific values with of()
LocalDate
public static LocalDate of(int year, int month, int dayOfMonth)
public static LocalDate of(int year, Month month, int dayOfMonth)
var launch1 = LocalDate.of(2026, Month.MARCH, 14);
var launch2 = LocalDate.of(2026, 3, 14); // same date
Months are 1-based in java.time: 1 is January and 12 is December. This is the one place where Java doesn't count from zero (the old Calendar API did, which caused many bugs). Month is an enum. Month.MARCH.getValue() returns 3, but ordinal() still returns 2, as for every enum.
LocalTime
public static LocalTime of(int hour, int minute)
public static LocalTime of(int hour, int minute, int second)
public static LocalTime of(int hour, int minute, int second, int nanoOfSecond)
LocalTime.of(7, 5); // 07:05
LocalTime.of(7, 5, 9); // 07:05:09
LocalTime.of(7, 5, 9, 1_000_000); // 07:05:09.001
LocalTime.of(7, 5, 9, 42); // 07:05:09.000000042
There's no of(int hour) method: you must pass at least the hour and minute. Hours run from 0 to 23, so LocalTime.of(24, 0) throws an exception. Use LocalTime.MIDNIGHT (00) or LocalTime.NOON (12) instead of writing those values out. The fraction is printed in groups of 3, 6 or 9 digits, depending on how precise the value is.
LocalDateTime
The integer versions take a year, a month (as an int or a Month), a day, an hour and a minute, plus optional seconds and nanoseconds:
public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute)
public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second)
public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
// ... and the same three with Month month
public static LocalDateTime of(LocalDate date, LocalTime time)
var a = LocalDateTime.of(2026, Month.MARCH, 14, 18, 45, 10);
var b = LocalDateTime.of(LocalDate.of(2026, 3, 14), LocalTime.of(18, 45, 10)); // equal to a
As with LocalTime, there's no version that stops at the hour: LocalDateTime.of(2026, 1, 1, 5) doesn't compile.
ZonedDateTime
For the exam, you need three factory methods:
public static ZonedDateTime of(int year, int month, int dayOfMonth,
int hour, int minute, int second, int nanoOfSecond, ZoneId zone)
public static ZonedDateTime of(LocalDate date, LocalTime time, ZoneId zone)
public static ZonedDateTime of(LocalDateTime dateTime, ZoneId zone)
var paris = ZoneId.of("Europe/Paris");
var z1 = ZonedDateTime.of(2026, 3, 14, 18, 45, 10, 0, paris);
var z2 = ZonedDateTime.of(LocalDate.of(2026, 3, 14), LocalTime.of(18, 45, 10), paris);
var z3 = ZonedDateTime.of(LocalDateTime.of(2026, 3, 14, 18, 45, 10), paris);
The all-integer version takes all seven numbers, including nanoseconds, and has no Month overload. Passing Month.MARCH there is a compile error. In real code, the two versions that take objects are much easier to read.
No constructors, and run-time validation
None of these classes has a public constructor. They use static factory methods instead, so this line doesn't compile:
var d = new LocalDate(); // DOES NOT COMPILE
Arguments are checked when the method runs, not when the code compiles. A value that's out of range compiles fine and then throws a java.time.DateTimeException, which is unchecked:
LocalDate.of(2026, 2, 29); // DateTimeException: Invalid date 'February 29' as '2026' is not a leap year
LocalDate.of(2026, 4, 31); // DateTimeException: Invalid date 'APRIL 31'
LocalDate.of(2026, 13, 1); // DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 13
You don't need to memorize the messages, but you should recognize that these lines compile and then fail at run time.
Changing values: plus and minus
All four types are immutable. Every plusX, minusX and withX call returns a new object and leaves the original unchanged:
var renewal = LocalDate.of(2026, Month.JANUARY, 31);
renewal = renewal.plusDays(1); // 2026-02-01
renewal = renewal.plusWeeks(2); // 2026-02-15
renewal = renewal.plusMonths(1); // 2026-03-15
renewal = renewal.plusYears(2); // 2028-03-15
If the result isn't assigned, the call does nothing useful. This is a favourite exam trap:
var renewal = LocalDate.of(2026, Month.JANUARY, 31);
renewal.plusDays(10); // result thrown away
System.out.println(renewal); // 2026-01-31
End of month and leap years
Adding months or years keeps the day of the month when it can. When that day doesn't exist in the target month, the result is moved back to the last valid day; no exception is thrown:
LocalDate.of(2026, 1, 31).plusMonths(1); // 2026-02-28 (2026 is not a leap year)
LocalDate.of(2028, 1, 31).plusMonths(1); // 2028-02-29 (2028 is)
LocalDate.of(2028, 2, 29).plusYears(1); // 2029-02-28
Once the day has been clamped, it stays clamped. Jan 31 + 1 month + 1 month is March 28, but Jan 31 + 2 months is March 31.
A year is a leap year if it is divisible by 4, except for years divisible by 100, which are leap years only if they are also divisible by 400. So 2028 and 2000 are leap years, but 2100 is not. isLeapYear() checks this for you.
Moving backward, and rolling over
The minus methods work the same way, and the larger fields adjust automatically when a smaller one crosses a boundary:
var shift = LocalDateTime.of(2026, Month.NOVEMBER, 1, 2, 15);
shift = shift.minusHours(3); // 2026-10-31T23:15 (back into October)
shift = shift.minusMinutes(20); // 2026-10-31T22:55
shift = shift.minusSeconds(5); // 2026-10-31T22:54:55 (seconds now appear)
Because each call returns a new object, the calls are often chained:
var shift = LocalDateTime.of(2026, Month.NOVEMBER, 1, 2, 15)
.minusHours(3).minusMinutes(20).minusSeconds(5);
A LocalTime has no date to roll into, so it simply wraps around the clock: LocalTime.of(22, 0).plusHours(5) is 03:00.
Which methods exist on which type?
A method compiles only if the type has the field it changes:
| Methods | LocalDate | LocalTime | LocalDateTime / ZonedDateTime |
|---|---|---|---|
plusYears minusYears withYear withDayOfYear | yes | no | yes |
plusMonths minusMonths withMonth | yes | no | yes |
plusWeeks minusWeeks | yes | no | yes |
plusDays minusDays withDayOfMonth | yes | no | yes |
plusHours minusHours withHour | no | yes | yes |
plusMinutes minusMinutes withMinute | no | yes | yes |
plusSeconds minusSeconds withSecond | no | yes | yes |
plusNanos minusNanos withNano | no | yes | yes |
LocalDate.of(2026, 1, 1).plusMinutes(1); // DOES NOT COMPILE: no time in a LocalDate
LocalTime.of(9, 0).plusDays(1); // DOES NOT COMPILE: no date in a LocalTime
Look carefully at long method chains: one wrong method anywhere makes the whole statement fail to compile.
Copying with changes: with methods
The withX methods return a copy with one field replaced:
var base = LocalDate.of(2026, Month.AUGUST, 20);
base.withDayOfMonth(1); // 2026-08-01
base.withMonth(2).withDayOfMonth(28); // 2026-02-28
base.withDayOfYear(100); // 2026-04-10 (the 100th day of the year)
base.withYear(2030); // 2030-08-20
Invalid values passed to with throw a DateTimeException, as they do for of. withDayOfMonth(31) on a June date fails.
Combining types: at methods and back
The atX methods combine the object with the argument to make a bigger type:
| Starting type | Method | Result |
|---|---|---|
LocalDate | atStartOfDay() | LocalDateTime at 00 |
LocalDate | atTime(int hour, int minute), atTime(h, m, s), atTime(h, m, s, nanos), atTime(LocalTime) | LocalDateTime |
LocalTime | atDate(LocalDate) | LocalDateTime |
LocalDateTime | atZone(ZoneId) | ZonedDateTime |
var day = LocalDate.of(2026, 8, 20);
day.atTime(9, 30); // 2026-08-20T09:30
day.atStartOfDay(); // 2026-08-20T00:00
LocalTime.of(9, 30).atDate(day).atZone(ZoneId.of("Asia/Tokyo"));
// 2026-08-20T09:30+09:00[Asia/Tokyo]
To go the other way, use toLocalDate(), toLocalTime() and (on ZonedDateTime) toLocalDateTime().
Getters and comparisons
These are used all the time in exam code:
getYear(),getMonth()(returns aMonth),getMonthValue()(returns anintfrom 1 to 12),getDayOfMonth(),getDayOfWeek()(aDayOfWeekenum),getDayOfYear(),getHour(),getMinute(),getSecond(),getNano().isBeforeandisAftercompare two values of the same type.LocalDate,LocalDateTimeandZonedDateTimealso haveisEqual, butLocalTimedoesn't: compare times withequalsorcompareTo. OnZonedDateTime, these methods compare the instant, so two different zones can beisEqual.equalscompares every field. ForZonedDateTime, that includes the zone, so the same instant in two different zones isisEqualbut notequals.compareToreturns a negative, zero or positive number. Don't assume -1: forLocalDate, it often returns the difference in years, months or days.
Some newer helpers are worth recognizing in real code:
LocalDate.datesUntil(end)(Java 9) returns aStream<LocalDate>.LocalDate.ofInstant(Java 9) creates a date from anInstantand a zone.LocalDate.EPOCH(Java 9) is 1970-01-01.toEpochDay()counts days since the epoch.
You don't need these for the exam.
What's current
java.time(Java 8) is the current date and time API.java.util.Date,CalendarandSimpleDateFormatare legacy. They aren't deprecated, but new code shouldn't use them.- The classes in this article didn't change in Java 22 through 25. Time zone rules update with each JDK's tzdata release, which matters only for real-world zone offsets.
Exam traps from this article
A complete example
The program creates all four types, shows end-of-month clamping in a billing schedule, demonstrates immutability, rolls a date-time back across midnight, shows one meeting in three zones, and catches invalid dates. It uses fixed values, so the output is the same on every run. Only the now() line depends on the clock, and it prints just the class name.
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Solution {
// Fixed values keep the output repeatable; real code would often start from now().
static final LocalDate START = LocalDate.of(2026, Month.JANUARY, 31);
static final LocalTime STANDUP = LocalTime.of(9, 30);
public static void main(String[] args) {
System.out.println("== The four types");
LocalDate date = LocalDate.of(2026, 3, 14);
LocalTime time = LocalTime.of(18, 45, 10);
LocalDateTime dateTime = LocalDateTime.of(date, time);
ZonedDateTime zoned = ZonedDateTime.of(dateTime, ZoneId.of("Europe/Paris"));
System.out.println("LocalDate: " + date);
System.out.println("LocalTime: " + time);
System.out.println("LocalDateTime: " + dateTime);
System.out.println("ZonedDateTime: " + zoned);
System.out.println("now() type: " + LocalDate.now().getClass().getSimpleName());
System.out.println("\n== toString hides zero seconds and nanos");
System.out.println(LocalTime.of(7, 5) + " | " + LocalTime.of(7, 5, 9) + " | "
+ LocalTime.of(7, 5, 9, 1_000_000) + " | " + LocalTime.of(7, 5, 9, 42));
System.out.println("\n== Monthly billing from Jan 31 (end-of-month clamping)");
LocalDate bill = START;
for (int i = 0; i < 4; i++) {
System.out.println("chained: " + bill);
bill = bill.plusMonths(1);
}
for (int i = 0; i < 4; i++) {
System.out.println("from start: " + START.plusMonths(i));
}
System.out.println("\n== Immutability: an ignored result changes nothing");
LocalDate deadline = LocalDate.of(2026, 6, 1);
deadline.plusWeeks(2); // result thrown away
System.out.println("ignored: " + deadline);
deadline = deadline.plusWeeks(2);
System.out.println("assigned: " + deadline);
System.out.println("\n== Going back across midnight");
LocalDateTime shift = LocalDateTime.of(2026, Month.NOVEMBER, 1, 2, 15)
.minusHours(3).minusMinutes(20).minusSeconds(5);
System.out.println(shift + " (" + shift.getDayOfWeek() + ")");
System.out.println("LocalTime wraps: " + LocalTime.of(22, 0).plusHours(5));
System.out.println("\n== with...() and at...()");
LocalDate base = LocalDate.of(2026, Month.AUGUST, 20);
System.out.println(base.withDayOfMonth(1) + " " + base.withMonth(2).withDayOfMonth(28)
+ " " + base.withDayOfYear(100));
System.out.println(base.atTime(STANDUP) + " " + base.atStartOfDay() + " "
+ STANDUP.atDate(base).atZone(ZoneId.of("Asia/Tokyo")));
System.out.println("\n== Same meeting, three zones");
ZonedDateTime call = ZonedDateTime.of(LocalDate.of(2026, 7, 8), STANDUP,
ZoneId.of("America/New_York"));
for (String id : new String[] {"America/New_York", "Europe/London", "Asia/Kolkata"}) {
System.out.println(call.withZoneSameInstant(ZoneId.of(id)));
}
System.out.println("\n== Invalid values throw DateTimeException at run time");
int[][] attempts = {{2026, 2, 29}, {2028, 2, 29}, {2026, 4, 31}, {2026, 13, 1}};
for (int[] a : attempts) {
try {
System.out.println("ok: " + LocalDate.of(a[0], a[1], a[2]));
} catch (DateTimeException e) {
System.out.println("failed: " + e.getMessage());
}
}
}
}
Output:
== The four types
LocalDate: 2026-03-14
LocalTime: 18:45:10
LocalDateTime: 2026-03-14T18:45:10
ZonedDateTime: 2026-03-14T18:45:10+01:00[Europe/Paris]
now() type: LocalDate
== toString hides zero seconds and nanos
07:05 | 07:05:09 | 07:05:09.001 | 07:05:09.000000042
== Monthly billing from Jan 31 (end-of-month clamping)
chained: 2026-01-31
chained: 2026-02-28
chained: 2026-03-28
chained: 2026-04-28
from start: 2026-01-31
from start: 2026-02-28
from start: 2026-03-31
from start: 2026-04-30
== Immutability: an ignored result changes nothing
ignored: 2026-06-01
assigned: 2026-06-15
== Going back across midnight
2026-10-31T22:54:55 (SATURDAY)
LocalTime wraps: 03:00
== with...() and at...()
2026-08-01 2026-02-28 2026-04-10
2026-08-20T09:30 2026-08-20T00:00 2026-08-20T09:30+09:00[Asia/Tokyo]
== Same meeting, three zones
2026-07-08T09:30-04:00[America/New_York]
2026-07-08T14:30+01:00[Europe/London]
2026-07-08T19:00+05:30[Asia/Kolkata]
== Invalid values throw DateTimeException at run time
failed: Invalid date 'February 29' as '2026' is not a leap year
ok: 2028-02-29
failed: Invalid date 'APRIL 31'
failed: Invalid value for MonthOfYear (valid values 1 - 12): 13
Points to notice:
- The billing loop shows the difference between chaining
plusMonths(1)(stuck on the 28th after February) and addingimonths to the start date (back to the 31st and 30th). deadline.plusWeeks(2);without an assignment leavesdeadlineunchanged.withZoneSameInstantkeeps the moment and changes the clock reading: 09 in New York is 14 in London and 19 in Kolkata in July.- February 29 is rejected in 2026 but accepted in 2028, and the
try/catchshows that the failures happen at run time.
Common questions
Should I use LocalDateTime or ZonedDateTime for timestamps?
To record when something actually happened, such as a log entry or a database event, use Instant or ZonedDateTime/OffsetDateTime. A LocalDateTime alone can't say which moment it is, because "09" happens at different times around the world. LocalDateTime suits local plans, such as "the alarm rings at 07".
Is java.util.Date deprecated?
Most of its constructors and methods have been deprecated since Java 1.1, but the class itself isn't. It survives for compatibility. java.time has conversion methods for older code: Date.toInstant() and Date.from(Instant).
Why does toString sometimes print seconds and sometimes not?
LocalTime.toString() prints the shortest ISO-8601 form that loses nothing. It omits seconds when they and the nanoseconds are zero, and prints the fraction in groups of 3, 6 or 9 digits.
How do I get a custom format like 14/03/2026?
Use a DateTimeFormatter, which is covered with localization in Chapter 11. toString() always uses ISO format.
Can ZoneId.of fail?
Yes. An unknown ID such as "Mars/Base" throws ZoneRulesException, and a badly formed one throws DateTimeException. Both are unchecked.
Summary
LocalDateholds a date,LocalTimea time,LocalDateTimeboth, andZonedDateTimeboth plus a zone. Get instances from the staticnow()andof()methods. There are no public constructors.- Months are 1-based, and the
Monthenum can be used instead of anint, except in the all-integerZonedDateTime.of. - Invalid values compile and then throw
DateTimeException.plusMonthsandplusYearsclamp to the last valid day instead. - All the types are immutable: assign the result of
plus,minusandwith, and remember thatLocalDatehas no time methods andLocalTimehas no date methods. atTime,atStartOfDay,atDateandatZonebuild bigger types, andtoLocalDate/toLocalTimetake them apart. Compare zoned times by converting them to UTC.
Practice quiz
Test yourself with the LocalDate, LocalTime, LocalDateTime and ZonedDateTime quiz: 10 exam-style questions with explanations.
Previous: Java Math API, BigInteger and BigDecimal (OCP 21)
Next: Java Period, Duration, Instant and Daylight Saving Time (OCP 21)
Related reading
- Java Math API, BigInteger and BigDecimal (OCP 21)
- Java Arrays: equals, compare, mismatch, Varargs and Multidimensional Arrays (OCP 21)
- Java Arrays: Creating, Sorting and Searching (OCP 21)
- Java String Equality: ==, equals, the String Pool and intern (OCP 21)
- Java StringBuilder: Mutability, Chaining and Methods (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.