Date and Time in Java
Since Java 8, the java.time package (JSR 310) is the standard way to work with dates and times. It replaced Date and Calendar, which were mutable, numbered months from 0 and were not thread-safe. This page explains which java.time class fits which kind of value, then shows date arithmetic, time zones and daylight saving changes, formatting and parsing, testing with a Clock, and the legacy traps you still meet in older code.
Contents
Choosing the right type
The key to java.timejava.time
| Class | Represents | Example | Use for |
|---|---|---|---|
LocalDate | A date without time or zone | 2026-11-14 | Birthdays, due dates, holidays |
LocalTime | A time of day without date or zone | 09:30 | Opening hours |
LocalDateTime | Date and time, no zone | 2026-11-14T09:30 | A wall-clock time whose zone is known from context |
ZonedDateTime | Date and time in a time zone with its rules | 2026-11-14T09:30-05:00[America/New_York] | Scheduling in a real place, including DST |
OffsetDateTime | Date and time with a fixed UTC offset | 2026-11-14T09:30-05:00 | Storing and exchanging timestamps, databases, APIs |
Instant | A point on the timeline, in UTC | 2026-11-14T14:30:00Z | Log entries, event times, measuring |
Duration | An exact amount of time in seconds and nanoseconds | PT1H30M | Timeouts, elapsed time |
Period | An amount in years, months and days | P1Y2M3D | Ages, subscriptions, "one month later" |
All of these classes are immutable and thread-safe: methods such as plusDays
Dates and times without a zone
The program starts from 31 January, the date that best shows how month arithmetic handles short months, and then adds days, moves to particular weekdays with adjusters, wraps a time past midnight and asks for a date that does not exist.
import java.time.DateTimeException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
public class LocalTypes {
public static void main(String[] args) {
LocalDate due = LocalDate.of(2026, Month.JANUARY, 31);
System.out.println("due: " + due + " (" + due.getDayOfWeek() + ")");
System.out.println("plus 1 month: " + due.plusMonths(1) + " (clamped to month end)");
System.out.println("plus 30 days: " + due.plusDays(30));
System.out.println("leap year 2028? " + LocalDate.of(2028, 1, 1).isLeapYear());
// Immutable: plusDays returns a new object
due.plusDays(1);
System.out.println("due unchanged: " + due);
LocalDate start = LocalDate.of(2026, 3, 15);
System.out.println("days between: " + ChronoUnit.DAYS.between(due, start));
System.out.println("first Monday of April: "
+ start.withMonth(4).with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)));
System.out.println("last day of Feb 2028: "
+ LocalDate.of(2028, 2, 1).with(TemporalAdjusters.lastDayOfMonth()));
LocalTime opens = LocalTime.of(9, 30);
System.out.println("opens + 10 hours: " + opens.plusHours(10));
System.out.println("opens + 16 hours: " + opens.plusHours(16) + " (wraps past midnight)");
LocalDateTime meeting = LocalDateTime.of(due, opens);
System.out.println("meeting: " + meeting);
System.out.println("isBefore start? " + meeting.toLocalDate().isBefore(start));
try {
LocalDate.of(2026, 2, 30);
} catch (DateTimeException e) {
System.out.println("Feb 30: " + e.getMessage());
}
}
}
Output:
due: 2026-01-31 (SATURDAY)
plus 1 month: 2026-02-28 (clamped to month end)
plus 30 days: 2026-03-02
leap year 2028? true
due unchanged: 2026-01-31
days between: 43
first Monday of April: 2026-04-06
last day of Feb 2028: 2028-02-29
opens + 10 hours: 19:30
opens + 16 hours: 01:30 (wraps past midnight)
meeting: 2026-01-31T09:30
isBefore start? true
Feb 30: Invalid date 'FEBRUARY 30'
- 31 January plus one month gives 28 February: there is no 31 February, so the day is clamped to the last valid day. Plus 30 days, in contrast, counts actual days and gives 2 March.
on its own line changed nothing, because the result was thrown away. Every "modifying" method returns a new object.due.plusDays(1) counts the days between two dates (43 from 31 January to 15 March 2026), andChronoUnit.DAYS.between find dates such as the first Monday of a month or the last day of February in a leap year.TemporalAdjusters wraps around midnight without changing any date, because it has none: 09:30 plus 16 hours is 01:30.LocalTime- Invalid values fail immediately:
throwsLocalDate.of(2026, 2, 30) rather than rolling over into March, as the oldDateTimeException did by default.Calendar
Time zones, instants and daylight saving time
A time zone is more than an offset: America/New_York
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class ZonesAndInstants {
public static void main(String[] args) {
ZoneId newYork = ZoneId.of("America/New_York");
ZoneId tokyo = ZoneId.of("Asia/Tokyo");
ZonedDateTime call = ZonedDateTime.of(LocalDateTime.of(2026, 3, 6, 18, 0), newYork);
System.out.println("call in New York: " + call);
System.out.println("same moment in Tokyo: " + call.withZoneSameInstant(tokyo));
System.out.println("as an Instant (UTC): " + call.toInstant());
// DST: on 2026-03-08 New York clocks jump from 02:00 to 03:00
ZonedDateTime before = ZonedDateTime.of(LocalDateTime.of(2026, 3, 7, 12, 0), newYork);
System.out.println("plusDays(1): " + before.plusDays(1));
System.out.println("plusHours(24): " + before.plusHours(24));
ZonedDateTime gap = ZonedDateTime.of(LocalDateTime.of(2026, 3, 8, 2, 30), newYork);
System.out.println("02:30 on the DST day becomes: " + gap.toLocalTime());
// Instant: a point on the timeline; Duration: an exact amount of time
Instant t1 = Instant.parse("2026-11-14T10:00:00Z");
Instant t2 = t1.plus(Duration.ofMinutes(90));
System.out.println("t2 = " + t2 + ", epoch seconds " + t2.getEpochSecond());
System.out.println("between: " + Duration.between(t1, t2) + " = "
+ Duration.between(t1, t2).toMinutes() + " minutes");
}
}
Output:
call in New York: 2026-03-06T18:00-05:00[America/New_York]
same moment in Tokyo: 2026-03-07T08:00+09:00[Asia/Tokyo]
as an Instant (UTC): 2026-03-06T23:00:00Z
plusDays(1): 2026-03-08T12:00-04:00[America/New_York]
plusHours(24): 2026-03-08T13:00-04:00[America/New_York]
02:30 on the DST day becomes: 03:30
t2 = 2026-11-14T11:30:00Z, epoch seconds 1794655800
between: PT1H30M = 90 minutes
- 18:00 in New York is 08:00 the next day in Tokyo and 23:00 UTC:
keeps the moment and changes the wall-clock time. (withZoneSameInstant does the opposite.)withZoneSameLocal - Across the DST change,
kept the wall-clock time, 12:00, whileplusDays(1) added exactly 24 hours and landed on 13:00, because that day was only 23 hours long. Which one is right depends on the meaning: "same time tomorrow" or "exactly 24 hours later".plusHours(24) - 02:30 did not exist on 8 March in New York.
moved it forward by the length of the gap, to 03:30, rather than failing.ZonedDateTime - An
is the same everywhere; it prints in UTC (theInstant ), andZ gives seconds since 1970-01-01T00:00Z.getEpochSecond measures the exact time between two instants.Duration.between
Periods, formatting and parsing
The program computes an age with Period
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Locale;
public class PeriodsAndFormatting {
public static void main(String[] args) {
LocalDate born = LocalDate.of(1990, 7, 21);
LocalDate today = LocalDate.of(2026, 11, 14); // fixed so the output is stable
Period age = Period.between(born, today);
System.out.println("age: " + age.getYears() + " years, " + age.getMonths()
+ " months, " + age.getDays() + " days (" + age + ")");
DateTimeFormatter us = DateTimeFormatter.ofPattern("MM/dd/yyyy");
DateTimeFormatter uk = DateTimeFormatter.ofPattern("EEEE, d MMMM uuuu", Locale.UK);
DateTimeFormatter fr = DateTimeFormatter.ofPattern("EEEE d MMMM uuuu", Locale.FRANCE);
System.out.println("US: " + today.format(us));
System.out.println("UK: " + today.format(uk));
System.out.println("French: " + today.format(fr));
System.out.println("ISO: " + LocalDateTime.of(today, LocalTime.NOON));
LocalDate parsed = LocalDate.parse("03/09/2026", us);
System.out.println("03/09/2026 as MM/dd/yyyy: " + parsed.getMonth()
+ " " + parsed.getDayOfMonth());
try {
LocalDate.parse("2026-13-01");
} catch (DateTimeParseException e) {
System.out.println("bad date: " + e.getMessage());
}
// The yyyy vs YYYY trap: Y is the week-based year
LocalDate dec29 = LocalDate.of(2025, 12, 29);
String calendarYear = dec29.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String weekYear = dec29.format(DateTimeFormatter.ofPattern("YYYY-MM-dd", Locale.UK));
System.out.println("yyyy: " + calendarYear + ", YYYY: " + weekYear);
}
}
Output:
age: 36 years, 3 months, 24 days (P36Y3M24D)
US: 11/14/2026
UK: Saturday, 14 November 2026
French: samedi 14 novembre 2026
ISO: 2026-11-14T12:00
03/09/2026 as MM/dd/yyyy: MARCH 9
bad date: Text '2026-13-01' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 13
yyyy: 2025-12-29, YYYY: 2026-12-29
gives years, months and days separately (36 years, 3 months, 24 days). It is the right tool for ages; aPeriod.between would count seconds and ignore the calendar.Duration- Patterns use letters:
day,d month number,MM month name,MMMM weekday name,EEEE oruuuu year. Month and day names come from theyyyy , which is why the French line reads "samedi 14 novembre 2026". Without a locale, the JVM's default is used, so pass one explicitly for output that must not vary.Locale - The same text means different dates with different patterns: "03/09/2026" parsed as
is 9 March; in most of Europe it means 3 September. For data exchange, use ISO 8601 (MM/dd/yyyy ), which2026-03-09 andtoString use by default.parse is the week-based year, not the calendar year. 29 December 2025 belongs to week 1 of 2026, soYYYY printed 2026-12-29, a date a whole year off. This bug appears every year around New Year in software that usedYYYY by mistake.YYYY
Tricky cases: overlaps, month arithmetic, lenient parsing and testing
These five cases compile cleanly and pass tests on most days, which is what makes them dangerous. Each one is shown with a date that triggers it.
import java.time.Clock;
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.time.format.ResolverStyle;
public class TrickyCases {
// Code that asks a Clock for "now" can be tested with a fixed time
static boolean isExpired(LocalDate expiry, Clock clock) {
return LocalDate.now(clock).isAfter(expiry);
}
public static void main(String[] args) {
ZoneId newYork = ZoneId.of("America/New_York");
// 1. Fall back: on 2026-11-01, 01:30 happens twice in New York
LocalDateTime twice = LocalDateTime.of(2026, 11, 1, 1, 30);
ZonedDateTime first = ZonedDateTime.of(twice, newYork);
System.out.println("01:30 on the fall-back day: " + first.getOffset()
+ ", later one: " + first.withLaterOffsetAtOverlap().getOffset());
// 2. Month arithmetic is not reversible
LocalDate jan31 = LocalDate.of(2026, 1, 31);
System.out.println("Jan 31 + 1 month - 1 month = " + jan31.plusMonths(1).minusMonths(1));
// 3. Parsing is lenient about days by default; STRICT needs uuuu instead of yyyy
DateTimeFormatter smart = DateTimeFormatter.ofPattern("uuuu-MM-dd");
System.out.println("smart parse of 2026-02-30: " + LocalDate.parse("2026-02-30", smart));
DateTimeFormatter strict = smart.withResolverStyle(ResolverStyle.STRICT);
try {
LocalDate.parse("2026-02-30", strict);
} catch (DateTimeParseException e) {
System.out.println("strict parse of 2026-02-30: DateTimeParseException");
}
// 4. A fixed Clock makes "today" testable
Clock fixed = Clock.fixed(Instant.parse("2026-11-14T12:00:00Z"), ZoneId.of("UTC"));
System.out.println("expired 2026-11-13 on fixed date: "
+ isExpired(LocalDate.of(2026, 11, 13), fixed));
System.out.println("expired 2026-11-14 on fixed date: "
+ isExpired(LocalDate.of(2026, 11, 14), fixed));
// 5. The same instant is a different date in different zones
Instant late = Instant.parse("2026-11-14T23:30:00Z");
System.out.println("23:30 UTC is " + late.atZone(ZoneId.of("Asia/Kolkata")).toLocalDate()
+ " in India and " + late.atZone(newYork).toLocalDate() + " in New York");
}
}
Output:
01:30 on the fall-back day: -04:00, later one: -05:00
Jan 31 + 1 month - 1 month = 2026-01-28
smart parse of 2026-02-30: 2026-02-28
strict parse of 2026-02-30: DateTimeParseException
expired 2026-11-13 on fixed date: true
expired 2026-11-14 on fixed date: false
23:30 UTC is 2026-11-15 in India and 2026-11-14 in New York
- On 1 November 2026, New York clocks go back from 02:00 to 01:00, so 01:30 happens twice: first at UTC-4, then again at UTC-5.
picks the earlier offset by default;ZonedDateTime picks the other. Code that stores local times without an offset cannot tell these two moments apart.withLaterOffsetAtOverlap - 31 January plus one month is 28 February, and minus one month is 28 January, not 31 January. Month arithmetic clamps, so it is not reversible. Compute from the original date each time (start plus n months) rather than adding one month repeatedly.
- With the default "smart" resolver,
parsed successfully as 28 February.2026-02-30 rejects it. In strict mode the year must be writtenResolverStyle.STRICT ;uuuu means "year of era" and also needs an era field, so strict parsing withyyyy fails even for valid dates.yyyy - Calling
inside business code makes it untestable. Taking aLocalDate.now() lets tests passClock , as here, while production passesClock.fixed(...) .Clock.systemDefaultZone() - One instant is a different calendar date in different places: 23:30 UTC on 14 November is already 15 November in India. Decide in which zone a "date" is meant before converting an
to aInstant .LocalDate
The legacy API: Date, Calendar and SimpleDateFormat
Older libraries and JDBC code still use java.util.DateCalendarSimpleDateFormatjava.time
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
public class LegacyDates {
public static void main(String[] args) throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // stable output
// 1. Calendar months start at 0
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2026, 1, 14); // 1 means February
System.out.println("Calendar.set(2026, 1, 14): " + cal.getTime());
// 2. Date is mutable: a "copy" held elsewhere changes too
Date deadline = cal.getTime();
List<Date> stored = new ArrayList<>(List.of(deadline));
deadline.setTime(0);
System.out.println("stored date after setTime(0): " + stored.get(0));
// 3. SimpleDateFormat is not thread-safe: share one between threads and parse
SimpleDateFormat shared = new SimpleDateFormat("yyyy-MM-dd");
Set<String> results = Collections.synchronizedSet(new HashSet<>());
List<Thread> threads = new ArrayList<>();
for (int t = 0; t < 4; t++) {
String text = "2026-0" + (t + 1) + "-1" + t;
threads.add(Thread.ofPlatform().start(() -> {
for (int i = 0; i < 2_000; i++) {
try {
Date d = shared.parse(text);
String back = new SimpleDateFormat("yyyy-MM-dd").format(d);
if (!back.equals(text)) {
results.add("wrong");
}
} catch (ParseException | RuntimeException e) {
results.add(e.getClass().getSimpleName());
}
}
}));
}
for (Thread t : threads) {
t.join();
}
System.out.println("shared SimpleDateFormat, 4 threads: problems seen = "
+ !results.isEmpty());
// 4. Converting between the old and new APIs
Date old = Date.from(Instant.parse("2026-11-14T10:00:00Z"));
Instant instant = old.toInstant();
LocalDate local = instant.atZone(ZoneId.of("Asia/Tokyo")).toLocalDate();
System.out.println("Date -> Instant -> LocalDate in Tokyo: " + instant + " -> " + local);
}
}
Output:
Calendar.set(2026, 1, 14): Sat Feb 14 00:00:00 UTC 2026
stored date after setTime(0): Thu Jan 01 00:00:00 UTC 1970
shared SimpleDateFormat, 4 threads: problems seen = true
Date -> Instant -> LocalDate in Tokyo: 2026-11-14T10:00:00Z -> 2026-11-14
months are numbered from 0, soCalendar means 14 February. Off-by-one-month bugs were common.set(2026, 1, 14) is mutable. The list kept a reference to the sameDate , soDate changed the "stored" deadline to 1 January 1970. Every class that held asetTime(0) had to copy it defensively.Date keeps parsing state in fields, so one instance shared by threads produces wrong dates or exceptions. Four threads parsing different dates with one shared formatter produced problems on every run.SimpleDateFormat is immutable and safe to share as a constant.DateTimeFormatter andDate.from(Instant) convert between the APIs; from thedate.toInstant() , choose a zone to get local values. For JDBC, drivers that support JDBC 4.2 read and writeInstant ,LocalDate andLocalDateTime directly withOffsetDateTime andgetObject .setObject
Rules for working with time
| Situation | Use |
|---|---|
| Recording when something happened | Instant |
| Timestamps in databases and JSON | OffsetDateTimeInstant |
| Future events in a real place, such as a 9:00 meeting | LocalDateTimeZoneId |
| Dates with no time, such as birthdays | LocalDate |
| "Same time tomorrow" | plusDaysZonedDateTime |
| "Exactly 24 hours later", timeouts | DurationInstant |
| Parsing user input | DateTimeFormatteruuuuLocaleResolverStyle.STRICT |
| Current time in business logic | A Clocknow() |
| Old APIs | Convert to java.timetoInstant |
Measuring how long code takes is a different job: use System.nanoTime