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.time is that it has a separate class for each kind of time value, and choosing the right one prevents most bugs. A birthday is a date with no time and no zone. A meeting is a local date and time in a particular zone. A log entry is a single moment on the global timeline. These are different things, and java.time makes you say which one you mean.

The main java.time classes
ClassRepresentsExampleUse for
LocalDateA date without time or zone2026-11-14Birthdays, due dates, holidays
LocalTimeA time of day without date or zone09:30Opening hours
LocalDateTimeDate and time, no zone2026-11-14T09:30A wall-clock time whose zone is known from context
ZonedDateTimeDate and time in a time zone with its rules2026-11-14T09:30-05:00[America/New_York]Scheduling in a real place, including DST
OffsetDateTimeDate and time with a fixed UTC offset2026-11-14T09:30-05:00Storing and exchanging timestamps, databases, APIs
InstantA point on the timeline, in UTC2026-11-14T14:30:00ZLog entries, event times, measuring
DurationAn exact amount of time in seconds and nanosecondsPT1H30MTimeouts, elapsed time
PeriodAn amount in years, months and daysP1Y2M3DAges, subscriptions, "one month later"

All of these classes are immutable and thread-safe: methods such as plusDays return a new object. They are in the JDK since Java 8, designed under JSR 310 by the author of the Joda-Time library.

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.

Java
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:

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.
  • due.plusDays(1) on its own line changed nothing, because the result was thrown away. Every "modifying" method returns a new object.
  • ChronoUnit.DAYS.between counts the days between two dates (43 from 31 January to 15 March 2026), and TemporalAdjusters find dates such as the first Monday of a month or the last day of February in a leap year.
  • LocalTime wraps around midnight without changing any date, because it has none: 09:30 plus 16 hours is 01:30.
  • Invalid values fail immediately: LocalDate.of(2026, 2, 30) throws DateTimeException rather than rolling over into March, as the old Calendar did by default.

Time zones, instants and daylight saving time

A time zone is more than an offset: America/New_York is UTC-5 in winter and UTC-4 in summer, and its rules say when it switches. The program schedules a call in New York, shows it in Tokyo and UTC, and then crosses the 8 March 2026 change to daylight saving time, when New York clocks jump from 02:00 to 03:00.

Java
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:

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: withZoneSameInstant keeps the moment and changes the wall-clock time. (withZoneSameLocal does the opposite.)
  • Across the DST change, plusDays(1) kept the wall-clock time, 12:00, while plusHours(24) 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".
  • 02:30 did not exist on 8 March in New York. ZonedDateTime moved it forward by the length of the gap, to 03:30, rather than failing.
  • An Instant is the same everywhere; it prints in UTC (the Z), and getEpochSecond gives seconds since 1970-01-01T00:00Z. Duration.between measures the exact time between two instants.

Periods, formatting and parsing

The program computes an age with Period, formats one date in three styles and two languages, parses a US-style date, rejects an impossible month, and shows the pattern letter that produces the wrong year a few days each December. The "today" date is fixed so the output does not change from day to day.

Java
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:

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
  • Period.between gives years, months and days separately (36 years, 3 months, 24 days). It is the right tool for ages; a Duration would count seconds and ignore the calendar.
  • Patterns use letters: d day, MM month number, MMMM month name, EEEE weekday name, uuuu or yyyy year. Month and day names come from the Locale, 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.
  • The same text means different dates with different patterns: "03/09/2026" parsed as MM/dd/yyyy is 9 March; in most of Europe it means 3 September. For data exchange, use ISO 8601 (2026-03-09), which toString and parse use by default.
  • YYYY is the week-based year, not the calendar year. 29 December 2025 belongs to week 1 of 2026, so YYYY printed 2026-12-29, a date a whole year off. This bug appears every year around New Year in software that used YYYY by mistake.

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.

Java
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:

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
  1. 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. ZonedDateTime picks the earlier offset by default; withLaterOffsetAtOverlap picks the other. Code that stores local times without an offset cannot tell these two moments apart.
  2. 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.
  3. With the default "smart" resolver, 2026-02-30 parsed successfully as 28 February. ResolverStyle.STRICT rejects it. In strict mode the year must be written uuuu; yyyy means "year of era" and also needs an era field, so strict parsing with yyyy fails even for valid dates.
  4. Calling LocalDate.now() inside business code makes it untestable. Taking a Clock lets tests pass Clock.fixed(...), as here, while production passes Clock.systemDefaultZone().
  5. 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 Instant to a LocalDate.

The legacy API: Date, Calendar and SimpleDateFormat

Older libraries and JDBC code still use java.util.Date, Calendar and SimpleDateFormat. The program shows the three problems that led to their replacement, and how to convert to java.time at the boundary. The default time zone is set to UTC so the printed dates do not depend on the machine.

Java
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:

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
  • Calendar months are numbered from 0, so set(2026, 1, 14) means 14 February. Off-by-one-month bugs were common.
  • Date is mutable. The list kept a reference to the same Date, so setTime(0) changed the "stored" deadline to 1 January 1970. Every class that held a Date had to copy it defensively.
  • SimpleDateFormat 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. DateTimeFormatter is immutable and safe to share as a constant.
  • Date.from(Instant) and date.toInstant() convert between the APIs; from the Instant, choose a zone to get local values. For JDBC, drivers that support JDBC 4.2 read and write LocalDate, LocalDateTime and OffsetDateTime directly with getObject and setObject.

Rules for working with time

Recommendations
SituationUse
Recording when something happenedInstant, stored in UTC
Timestamps in databases and JSONOffsetDateTime or Instant, in ISO 8601 text
Future events in a real place, such as a 9:00 meetingLocalDateTime plus the ZoneId, converted when needed; zone rules can change before the date
Dates with no time, such as birthdaysLocalDate
"Same time tomorrow"plusDays on a ZonedDateTime
"Exactly 24 hours later", timeoutsDuration on an Instant
Parsing user inputDateTimeFormatter with uuuu, an explicit Locale and ResolverStyle.STRICT
Current time in business logicA Clock passed in, not now() with no arguments
Old APIsConvert to java.time at the boundary with toInstant

Measuring how long code takes is a different job: use System.nanoTime for that, since wall-clock time can jump; see the JMH page.