Skip to content
Tutorials Center
My learning

Topics

Lesson 106 of 201 ยท Working with Data

Dates and Times

Learn the java.time API - LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Instant, Duration, Period, TemporalAdjusters and DateTimeFormatter, plus why to avoid Date.

Dates and times look simple until you try to get them right. Months have 28 to 31 days, years can be leap years, clocks jump forward and back for daylight saving time, "tomorrow at 9:00" depends on where you are, and a server in Frankfurt and a phone in Tokyo disagree about what day it is. Bugs here are expensive: double-charged subscriptions, missed meetings, reports that skip an hour every spring.

Java's answer is the java.time package (Java 8). Its classes are immutable, thread-safe, precise about what each value means, and built on the ISO-8601 standard. This lesson walks through the core types (LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Instant), doing arithmetic with Duration, Period and ChronoUnit, adjusting dates with TemporalAdjusters, formatting and parsing with DateTimeFormatter, handling time zones and daylight saving time, and why the old java.util.Date and Calendar classes belong in the past.

Choosing the right type

The most important skill is picking the type that matches what your value means:

Type Example Meaning
LocalDate 2025-07-14 A calendar date with no time or zone: a birthday, a due date
LocalTime 09:30 A wall-clock time with no date: opening hours
LocalDateTime 2025-07-14T09:30 Date + time, but no zone: not a point on the timeline yet
ZonedDateTime 2025-07-14T09:30+02:00[Europe/Paris] Date + time in a specific time zone, with its rules
OffsetDateTime 2025-07-14T09:30+02:00 Date + time with a fixed UTC offset (common in APIs and databases)
Instant 2025-07-14T07:30:00Z An exact point on the UTC timeline: timestamps, logs
Duration PT1H30M An amount of time in seconds and nanoseconds
Period P1Y2M3D An amount of time in years, months and days

"Local" doesn't mean "in my time zone"; it means "no time zone at all." A LocalDateTime of 9:30 on July 14 is a different moment in Paris and in Lima. When you need an exact moment, use Instant or ZonedDateTime.

Creating and reading dates and times

Every type has now() for the current value, of(...) for specific values and parse(...) for ISO-8601 text. Getters like getYear(), getMonth() and getDayOfWeek() read the parts.

Java Creating dates and times and reading their parts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Unlike the old API, months are numbered 1 to 12 (or use the Month enum), and invalid values such as February 30 throw a DateTimeException instead of silently rolling over into March. YearMonth, MonthDay and Year cover partial dates like a credit-card expiry or a yearly anniversary.

Date arithmetic is immutable

Methods like plusDays, minusMonths and withDayOfMonth return a new object; they never change the original. Forgetting to use the result is a classic bug:

Java
LocalDate due = LocalDate.of(2025, 3, 1);
due.plusDays(14);            // result thrown away: due is unchanged!
due = due.plusDays(14);      // correct

Month arithmetic handles short months by clamping to the last valid day, which matters for billing:

Java plus, minus, with and month-end clamping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that plusMonths(1).plusMonths(1) gives February 29 + 1 month = March 29, while plusMonths(2) gives March 31. For recurring schedules, always add n months to the original date.

Duration, Period and ChronoUnit

There are two ways to express "an amount of time," and they behave differently:

  • Duration is exact elapsed time in seconds and nanoseconds: Duration.ofMinutes(90), Duration.between(startInstant, endInstant). Use it with times, Instant and ZonedDateTime.
  • Period is calendar time in years, months and days: Period.ofMonths(1), Period.between(date1, date2). "One month" isn't a fixed number of seconds, so only Period can represent it.

When you need a single number ("how many days until..."), use ChronoUnit.DAYS.between(a, b) (or HOURS, MINUTES, WEEKS, MONTHS...). It counts complete units.

Java Duration, Period and ChronoUnit between two values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

toString uses ISO-8601 notation: PT8H18M means a period of time of 8 hours 18 minutes, and P3Y5M15D means 3 years, 5 months, 15 days. The toXxxPart() methods (Java 9) give the individual components, which is handy for formatting.

Adjusters and DayOfWeek

"The last day of the month," "next Friday," "the first Monday of September": these are temporal adjusters. Pass one to with(...):

Java TemporalAdjusters and DayOfWeek

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

DayOfWeek values run from MONDAY (1) to SUNDAY (7), following ISO-8601. datesUntil (Java 9) returns a stream of dates, which makes calendar calculations short and readable.

Formatting and parsing with DateTimeFormatter

toString() and parse() use ISO-8601 (2025-07-14), the right choice for files, logs and APIs. For people, use a DateTimeFormatter:

  • Predefined ISO formatters: DateTimeFormatter.ISO_LOCAL_DATE, ISO_INSTANT, ...
  • Localized styles: DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(locale) adapts to the reader's language and conventions.
  • Patterns: DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm", Locale.US).

Common pattern letters: uuuu or yyyy year, MM month number, MMM/MMMM month name, dd day, EEE/EEEE weekday name, HH hour 0โ€“23, hh hour 1โ€“12 with a for AM/PM, mm minutes, ss seconds, VV zone ID, XXX offset. Formatters are immutable and thread-safe, so store them in static final constants.

Java Formatting, parsing and the YYYY trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

YYYY is not the year. It's the week-based year, which differs from the calendar year for a few days around New Year. A pattern like YYYY-MM-dd works almost all year and then prints "2025-12-30" on December 30, 2024. Use uuuu or yyyy. Similarly, DD is day-of-year and mm is minutes, not months.

Always pass a Locale when your pattern contains names (MMMM, EEEE, a); otherwise the server's default locale decides the language. See Locales and Internationalization for more.

DateTimeFormatterBuilder: custom formatters and parsers

ofPattern covers most needs, but some formats cannot be written as a single pattern string: optional parts, default values for missing fields, or case-insensitive month names. DateTimeFormatterBuilder assembles a formatter from pieces, and ofPattern itself is just a builder shortcut. The most useful methods:

Method What it does
appendValue(field, width) a number with a fixed width (appendValue(MONTH_OF_YEAR, 2) gives 03)
appendFraction(field, min, max, decimalPoint) a fraction such as milliseconds; trailing zeros beyond min are dropped
appendLiteral(text) fixed text such as - or T
appendPattern("MMM uuuu") embeds a normal pattern inside a builder
optionalStart() / optionalEnd() a section that parsing may skip and formatting prints only if the value exists
parseDefaulting(field, value) supplies a value when the input lacks that field
parseCaseInsensitive() accepts DECEMBER for December (the default is case-sensitive)
parseLenient() relaxes number and text rules for parsing
toFormatter(Locale) finishes the builder; always pass a locale
Java Optional sections, defaults and case-insensitive parsing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first formatter accepts a timestamp with no seconds, with seconds, or with milliseconds, because each optional section is skipped when the input ends. appendFraction(..., 0, 3, true) printed .25 rather than .250: with a minimum width of 0, trailing zeros are dropped. parseDefaulting is the usual fix when a field is missing, because a LocalDate cannot be built from a month and a year alone.

ChronoField: reading and changing single fields

Every date-time type is a bag of fields, described by the ChronoField enum: YEAR, MONTH_OF_YEAR, DAY_OF_YEAR, DAY_OF_WEEK, MINUTE_OF_DAY, INSTANT_SECONDS, and about 30 more. You read one with get(field) (or getLong when the value can exceed an int, like epoch seconds) and replace one with with(field, value), which returns a new object like every other immutable operation. Each type supports only the fields that make sense for it: asking a LocalDate for HOUR_OF_DAY throws UnsupportedTemporalTypeException, and isSupported(field) checks first. field.range() gives the legal values in general, and date.range(field) the legal values for that specific date. Locale-sensitive fields, such as week of year, live in WeekFields.of(locale).

Java ChronoField access and ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same ChronoField constants are what appendValue and parseDefaulting take, so the two halves of this section fit together: the builder decides which fields a string carries, and the temporal types expose them.

Time zones, Instant and daylight saving time

A time zone like Europe/Berlin or America/New_York is a set of rules: which UTC offset applies on which dates, including daylight saving changes. A fixed offset like +02:00 is just a number. Prefer region IDs (ZoneId.of("Asia/Tokyo")) over offsets for anything involving future dates, because rules change.

Instant is the universal representation of a moment. Store and transmit instants (or OffsetDateTime / UTC), and convert to a ZonedDateTime only to show times to people.

Java Zones, Instant and a DST gap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last two lines show why types matter: on the night clocks jump forward, "one day later" (same wall-clock time, plusDays) and "24 hours later" (plusHours, exact elapsed time) are different moments. Neither is wrong; choose the one your business rule means. A daily reminder should use plusDays; a 24-hour token expiry should use a Duration on an Instant.

Testable code with Clock

Code that calls LocalDate.now() is hard to test, because the answer changes every day. Every now() method has an overload that takes a Clock. Inject a clock into your classes, use Clock.systemDefaultZone() (or Clock.systemUTC()) in production and Clock.fixed(...) in tests:

Java
class TrialChecker {
    private final Clock clock;

    TrialChecker(Clock clock) {
        this.clock = clock;
    }

    boolean isExpired(LocalDate trialEnd) {
        return LocalDate.now(clock).isAfter(trialEnd);
    }
}

// In a test:
Clock fixed = Clock.fixed(Instant.parse("2025-05-01T10:00:00Z"), ZoneOffset.UTC);
new TrialChecker(fixed).isExpired(LocalDate.of(2025, 4, 30));   // true, always

Why not java.util.Date and Calendar?

Before Java 8, Java had java.util.Date, Calendar and SimpleDateFormat. You'll still meet them in old code and some libraries, but avoid them in new code:

  • Mutable: date.setTime(...) changes a shared object; a Date stored in a field can be modified by anyone holding a reference.
  • Misleading: Date is really an instant, but its toString prints it in the JVM's default zone. Months in Calendar start at 0, so Calendar.MARCH is 2.
  • Lenient by default: February 30 silently becomes March 2.
  • Not thread-safe: a shared SimpleDateFormat corrupts results under concurrency.
  • One class for everything: no separate types for a date, a time or a duration.

When you must interoperate, convert at the boundary: date.toInstant() and Date.from(instant), calendar.toInstant(), and for JDBC, java.sql.Date.valueOf(localDate) / sqlDate.toLocalDate(). Modern JDBC drivers support java.time types directly (Advanced Java: JDBC).

Date and time programs

These four short programs are the formatting tasks people ask for most often. They all rely on DateTimeFormatter from the section above, plus Locale and zone conversion.

12-hour clock with AM and PM

In a pattern, HH is the hour from 00 to 23 and hh is the hour from 01 to 12; the letter a prints the AM/PM marker. Always pass a Locale when you use a (or any month or day name), because the text comes from locale data. Midnight is 12:00 AM and noon is 12:00 PM, which surprises people the first time.

Java AM/PM formatting and parsing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

One date in many formats

Printing the same LocalDate in different shapes is only a matter of choosing a pattern. Letters repeat to choose a width: M is 3, MM is 03, MMM is Mar and MMMM is March; EEE and EEEE are the short and long day names; D is the day of the year. yyyy means year-of-era and uuuu means proleptic year; they agree for modern dates, and uuuu is the safer choice with strict parsing. Year and Month give you more calendar facts without any formatter.

Java Calendar date in different formats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Text inside single quotes ('Day', 'of') is printed literally; an unquoted letter that is not a pattern letter throws an IllegalArgumentException, and one that is a pattern letter silently prints something you did not mean (an unquoted D in Day would print the day of the year).

Country-specific formats with Locale

Different countries write the same date differently: 3/9/25, 09/03/2025, 09.03.25, 2025/03/09. Do not hard-code those shapes. Ask Java for the localized style with ofLocalizedDate(FormatStyle.FULL/LONG/MEDIUM/SHORT) and attach a locale with withLocale. Day and month names follow the locale too.

Java Localized dates for six locales

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The exact text comes from the JDK's built-in locale data (CLDR), which changes between Java releases. Short formats in particular get small updates, so your output on another JDK may differ slightly from what you see here.

Local time to GMT

To convert a wall-clock time to GMT or UTC, first say where the wall clock was: atZone(ZoneId) turns a LocalDateTime into a ZonedDateTime. Then withZoneSameInstant shows the same moment in another zone. The conversion uses the zone's rules for that date, so New York is five hours behind UTC in January and four hours behind in July. Printing an Instant always gives UTC.

Java Convert local time to GMT and UTC

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Do not use ZoneId.systemDefault() for conversions that must give the same answer on every machine; name the zone explicitly, as above. More on zones and daylight saving time is in Time zones, Instant and daylight saving time.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? LocalDate d = LocalDate.of(2025, 1, 10); d.plusDays(5); IO.println(d);

    java.time objects are immutable. plusDays returns a new date that is thrown away here, so d still holds January 10.
  2. 2. What is LocalDate.of(2025, 1, 31).plusMonths(1)?

    Month arithmetic clamps to the last valid day of the target month. February 2025 has 28 days.
  3. 3. You need to store the exact moment an order was placed, for users worldwide. Which type fits best?

    An Instant is an unambiguous point on the UTC timeline. LocalDateTime has no zone, so it can't identify a moment by itself.
  4. 4. Which pattern correctly prints the calendar year, month and day?

    YYYY is the week-based year, mm is minutes and DD is the day of the year. uuuu (or yyyy) with MM and dd is correct.
  5. 5. Which type represents "3 months" correctly, even though months differ in length?

    Period stores years, months and days as calendar units. Duration is an exact number of seconds, which can't represent a month.

Summary

  • Use LocalDate, LocalTime and LocalDateTime for values without a zone, ZonedDateTime for local times in a place, and Instant for exact moments.
  • All java.time types are immutable: plusDays and friends return new objects. Month arithmetic clamps to the end of the month.
  • Duration measures exact time, Period measures calendar time, and ChronoUnit.X.between counts whole units.
  • TemporalAdjusters find "last day of month" or "next Friday"; DayOfWeek runs from Monday (1) to Sunday (7).
  • DateTimeFormatter formats and parses; use uuuu/yyyy, never YYYY, and pass a Locale for names.
  • Prefer region zone IDs, store Instants, and remember that plusDays(1) and 24 hours differ across DST changes.
  • Inject a Clock for testable code, and avoid Date, Calendar and SimpleDateFormat in new code.

Next: Regular Expressions, where you'll search, validate and transform text with Pattern and Matcher.