Study guide
11.2 Timestamps, Intervals, and Durations: `Instant`, `Period`, and `Duration`
Oracle Java SE 17 Developer Certified Professional 1Z0-829
Track your progress as you read
Finished sections get a check mark.
1 Introduction: The 1Z0-829 Exam
About the Java SE 17 Developer (1Z0-829) Exam
2 Chapter 1: Java Fundamentals & Language Basics
1.1 Primitive Types, Literals, Wrapper Classes, and Type Promotion/Casting 1.2 Local Variable Type Inference (`var`) Rules and Scoping 1.3 Operators, Precedence, Evaluation Order, and Short-Circuit Evaluation 1.4 Text Blocks, String Immutability, and StringBuilder APIs
3 Chapter 2: Program Flow & Decision Constructs
2.1 Conditional Branching with if/else and the Ternary Operator 2.2 Switch Statements and Switch Expressions 2.3 Iteration Constructs, Loop Control, and Branching Labels
4 Chapter 3: Object-Oriented Design & Class Mechanics
3.1 Class Declarations, Field/Method Signatures, and Access Modifiers 3.2 Constructors, Overloading, Initialization Order, and Garbage Collection 3.3 Inheritance, Method Overriding, Polymorphism, and `super`/`this` 3.4 Abstract Classes, Static Members, and Object Methods (`equals`, `hashCode`, `toString`)
5 Chapter 4: Advanced OOP: Interfaces, Records & Sealed Types
4.1 Interface Architecture: Default, Static, and Private Methods 4.2 Enumerations: Constants, Constructors, Methods, and Custom Bodies 4.3 Records: Canonical/Compact Constructors, Components, and Immutability 4.4 Sealed Classes and Interfaces: `permits`, Hierarchy Constraints, and Modifiers
6 Chapter 5: Pattern Matching & Nested Types
5.1 Pattern Matching for `instanceof` and Flow Scoping Mechanics 5.2 Nested Types: Member Inner, Static Nested, Local, and Anonymous Classes 5.3 Defensive Programming, Immutability Patterns, and Validation
7 Chapter 6: Generics, Collections & Arrays
6.1 Generic Classes, Interfaces, Methods, and Type Erasure 6.2 Bounded Type Parameters and Wildcards (PECS Rule) 6.3 Collections Framework: List, Set, Queue, and Deque APIs 6.4 The Map Interface, Sorting, Comparable, and Comparator 6.5 Arrays: Declaration, Initialization, Multidimensional Arrays, and the Arrays Utility Class
8 Chapter 7: Functional Programming & Lambda Expressions
7.1 Functional Interfaces and Lambda Syntax Rules 7.2 Standard Functional Interfaces in `java.util.function` 7.3 Method References: Static, Bound, Unbound, and Constructor References
9 Chapter 8: The Stream API
8.1 Stream Lifecycle: Creation, Pipeline Architecture, and Lazy Evaluation 8.2 Intermediate Stream Operations: Filtering, Mapping, Sorting, and Slicing 8.3 Terminal Stream Operations: Reduction, Matching, Finding, and Collecting 8.4 Primitive Streams (`IntStream`, `LongStream`, `DoubleStream`) and Numeric Statistics
10 Chapter 9: Advanced Streams & Collectors
9.1 The Optional Class: Safe Null Handling, Transformation, and Chaining 9.2 The Collectors API: Downstream Reductions, Grouping, and Partitioning 9.3 Parallel Streams: Fork/Join Pool, Spliterators, and Concurrency Pitfalls
11 Chapter 10: Exception Handling
10.1 The Java Exception Hierarchy: Checked vs. Unchecked Exceptions and Errors 10.2 Exception Constructs: `try-catch-finally`, Multi-Catch, and Rethrowing 10.3 Try-With-Resources, `AutoCloseable`, Suppressed Exceptions, and Custom Exceptions
12 Chapter 11: Date/Time API & Localization
11.1 Date and Time Core Types: `LocalDate`, `LocalTime`, `LocalDateTime` 11.2 Timestamps, Intervals, and Durations: `Instant`, `Period`, and `Duration` 11.3 Time Zones, Daylight Saving Time (DST) Offsets, and `ZonedDateTime` 11.4 Internationalization and Localization: `Locale`, `ResourceBundle`, and Formatters 11.5 Formatting and Parsing Messages, Numbers, Percentages, and Localized Dates
13 Chapter 12: Java Platform Module System (JPMS)
12.1 Module Architecture, `module-info.java`, and Module Paths 12.2 Module Directives: `requires`, `requires transitive`, `exports`, and Qualified Exports 12.3 Reflection, Deep Encapsulation, `opens`, and Open Modules 12.4 Services in JPMS (`uses`, `provides...with`), Migration Paths, and Tooling (`jlink`, `jdeps`) 12.5 Compiling and Packaging Code: Non-Modular JARs, Modular JARs, and Migration Strategies
14 Chapter 13: Concurrency & Multithreading
13.1 Thread Fundamentals, `Runnable`, `Callable`, and Thread Lifecycle 13.2 Memory Visibility, `volatile`, Intrinsic Locks, and Synchronization 13.3 The Concurrency Framework: `ExecutorService`, Thread Pools, and `Future` 13.4 Concurrent Collections, Atomic Variables, Explicit Locks, and `CompletableFuture`
15 Chapter 14: Java I/O and NIO.2
14.1 Classical I/O: Byte and Character Streams, Readers, Writers, and Buffering 14.2 Object Serialization, `Serializable`, `transient`, and `serialVersionUID` 14.3 NIO.2 Architecture: `Path`, `Paths`, and Basic `Files` Operations 14.4 Advanced NIO.2: Directory Walking, Streams (`Files.lines`, `walk`), and `WatchService`
16 Chapter 15: Accessing Databases with JDBC
15.1 JDBC Architecture, Drivers, `DriverManager`, and `DataSource` Connections 15.2 SQL Execution: `Statement`, `PreparedStatement`, and `CallableStatement` 15.3 `ResultSet` Navigation, Data Types, and Transaction Management (Commit, Rollback, Savepoints)
17 Chapter 16: Annotations & the Java Logging API
16.1 Standard Annotations: @Override, @FunctionalInterface, @Deprecated, @SuppressWarnings, and @SafeVarargs 16.2 Java Logging API Basics: Logger, Levels, Handlers, and Configuration
11.2 Timestamps, Intervals, and Durations: `Instant`, `Period`, and `Duration`
Key Takeaways Explain This Topic AI
Instant models a universal, machine-based point on the timeline representing seconds and nanoseconds offset from the Unix epoch (1970-01-01T00:00:00Z) in UTC.
Period encapsulates calendar-based amounts of years, months, and days; adding a Period to a LocalTime throws UnsupportedTemporalTypeException, and an Instant accepts only day-based periods (months or years throw).
Duration encapsulates exact machine-based amounts of time in seconds and nanoseconds (accessible as days, hours, minutes, seconds, nanos); it cannot be applied to LocalDate.
Methods on Period and Duration such as ofYears(), ofMonths(), and ofDays() are static factories that do not chain; chaining them resolves only the final static method call.
ChronoUnit.between() computes the whole elapsed units between two temporal objects, returning positive values if the end object is later than the start object and negative values if earlier.
Last updated: October 2026
11.2 Timestamps, Intervals, and Durations: Instant , Period , and Duration
Working effectively with time requires distinguishing between two distinct perspectives: human calendar time (years, months, weeks, days) and machine timeline points and durations (exact seconds, milliseconds, and nanoseconds). The Java SE 17 Date-Time API models these dimensions using Instant , Period , and Duration .
Machine Timeline: Instant
An Instant represents an instantaneous point on the global timeline, defined as an offset from the standard Unix epoch: January 1, 1970, 00:00:00 UTC (Zulu time) . It stores time as a 64-bit integer representing epoch seconds and a 32-bit integer representing nanoseconds of the second.
- Factory Methods and Conversions // Current instant from system clock in UTC
- Instant now = Instant.now();
- // Specific offsets from Unix epoch
- Instant epoch = Instant.ofEpochMilli(0); // 1970-01-01T00:00:00Z
- Instant specificSec = Instant.ofEpochSecond(1_000_000_000); // 2001-09-09T01:46:40Z
- // Parsing standard ISO-8601 UTC string (must include 'Z' or offset)
- Instant parsed = Instant.parse("2026-10-11T12:00:00Z");
- Characteristics and Limitations of Instant
Because Instant models the continuous physical timeline in UTC without human calendar semantics:
It contains no time zone (it is inherently pinned to UTC).
It has no concept of year, month, day, or day of week .
Calling instant.get(ChronoField.YEAR) or instant.get(ChronoField.DAY_OF_MONTH) compiles (since Instant implements TemporalAccessor ), but throws UnsupportedTemporalTypeException at runtime!
To bridge human calendar representations with machine timestamps, you must associate the Instant with a time zone ( ZoneId ) to produce a ZonedDateTime : Instant stamp = Instant.now();
- ZonedDateTime tokyoTime = stamp.atZone(ZoneId.of("Asia/Tokyo"));
- LocalDate localDateInTokyo = tokyoTime.toLocalDate();
- Human Calendar Amounts: Period
A Period represents an amount of time in terms of calendar-based units: years, months, and days .
- Factory Creation and Parsing
- Period instances are created using static factory methods: Period oneYear = Period.ofYears(1);
- Period twoMonths = Period.ofMonths(2);
Period threeWeeks = Period.ofWeeks(3); // Stored internally as 21 days!
Period fiveDays = Period.ofDays(5);
- // Compound period: 1 year, 6 months, and 15 days
- Period compound = Period.of(1, 6, 15);
- // Parsing ISO-8601 period format (prefixed with 'P')
- Period parsedPeriod = Period.parse("P1Y6M15D"); // 1 year, 6 months, 15 days
- Period twoWeeks = Period.parse("P2W"); // 14 days
- Modifying Temporals with Period
Period is designed to be added to or subtracted from date-bearing temporal objects ( LocalDate , LocalDateTime , ZonedDateTime ): LocalDate wedding = LocalDate.of(2026, Month.JUNE, 20);
- LocalDate anniversary = wedding.plus(Period.ofYears(1)); // 2027-06-20
- The Period Incompatibility Trap
A Period contains days, months, or years. It contains no hours, minutes, or seconds . If you attempt to add or subtract a Period from a LocalTime , the code compiles (because plus(TemporalAmount) accepts any TemporalAmount ), but throws UnsupportedTemporalTypeException at runtime: LocalTime bedtime = LocalTime.of(22, 0);
Period dayPeriod = Period.ofDays(1);
// COMPILES! But throws UnsupportedTemporalTypeException at runtime:
- // java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Days
- LocalTime failed = bedtime.plus(dayPeriod);
- Machine Time Amounts: Duration
A Duration represents an amount of time in terms of exact, machine-based units: seconds and nanoseconds . For convenience, the API provides helper methods to work with days, hours, and minutes, but internally these are always converted to exact seconds ( 1 day = 24 hours = 86 , 400 seconds 1 \text{ day} = 24 \text{ hours} = 86,400 \text{ seconds} 1 day = 24 hours = 86 , 400 seconds ).
- Factory Creation and Calculation Duration oneDay = Duration.ofDays(1); // 86,400 seconds
- Duration twoHours = Duration.ofHours(2); // 7,200 seconds
- Duration tenMinutes = Duration.ofMinutes(10); // 600 seconds
- Duration thirtySeconds = Duration.ofSeconds(30);
- Duration hundredMillis = Duration.ofMillis(100);
- // Calculating elapsed duration between two temporal points
- LocalTime start = LocalTime.of(9, 0);
- LocalTime end = LocalTime.of(10, 30);
- Duration elapsed = Duration.between(start, end); // PT1H30M (1 hour, 30 minutes)
- // Parsing ISO-8601 duration format (prefixed with 'PT' for time)
- Duration parsedDuration = Duration.parse("PT2H15M"); // 2 hours, 15 minutes
- The Duration Incompatibility Trap
A Duration tracks time in seconds and nanoseconds. A LocalDate contains only calendar dates and has no time components . If you attempt to add or subtract a Duration to or from a LocalDate , Java throws UnsupportedTemporalTypeException at runtime: LocalDate date = LocalDate.of(2026, Month.MAY, 1);
Duration twoHoursDuration = Duration.ofHours(2);
// COMPILES! But throws UnsupportedTemporalTypeException at runtime:
- // java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds
- LocalDate invalidDate = date.plus(twoHoursDuration);
Warning
Even Duration.ofDays(1) throws an exception when added to a LocalDate ! Although Duration has an ofDays() factory, it translates days into seconds ( 86 , 400 s 86,400\text{s} 86 , 400 s ). Because LocalDate cannot accept seconds, date.plus(Duration.ofDays(1)) immediately throws UnsupportedTemporalTypeException .
Comparison: Period vs. Duration
- Feature Period Duration
- Conceptual Domain Human calendar intervals Machine timeline intervals
- Units Supported Years, Months, Days Seconds, Nanoseconds (Days, Hours, Minutes)
Day Definition Variable (23, 24, or 25 hours depending on DST) Fixed ( 86 , 400 86,400 86 , 400 seconds exactly)
Compatible Types LocalDate , LocalDateTime , ZonedDateTime LocalTime , LocalDateTime , Instant , ZonedDateTime
Incompatible Types LocalTime (throws); Instant accepts only day-based periods, so months or years throw LocalDate (throws exception)
- ISO-8601 Format Starts with P (e.g., P1Y2M3D ) Starts with PT or P...T... (e.g., PT1H30M )
- The Static Factory Chaining Trap
A well-known trick pattern is the static method chaining illusion on Period and Duration .
In Java, static methods can be syntactically called on an instance reference or chained together, but static calls are resolved entirely by the compiler against the declaring class. They never operate on an accumulated instance : // What does this produce?
- Period period = Period.ofYears(1).ofMonths(2).ofDays(3);
- System.out.println(period); // PRINTS: P3D (3 days only!)
Why Does This Occur?
Period.ofYears(1) executes statically, returning a new Period representing 1 year ( P1Y ).
.ofMonths(2) is invoked. Because ofMonths is static , the compiler ignores the P1Y instance completely and evaluates Period.ofMonths(2) , returning a new Period of 2 months ( P2M ).
.ofDays(3) is invoked. Similarly, it is static , discarding the P2M instance and returning a new Period of 3 days ( P3D ).
The variable period receives only the 3-day period! // WRONG: Yields only 30 minutes!
Duration d = Duration.ofHours(5).ofMinutes(30);
// CORRECT way to create compound periods and durations:
- Period correctPeriod = Period.of(1, 2, 3); // 1 year, 2 months, 3 days
- Duration correctDuration = Duration.ofHours(5).plusMinutes(30); // 5 hours, 30 minutes
- Calculating Differences with ChronoUnit.between()
The java.time.temporal.ChronoUnit enum represents standard date-time units (from NANOS through FOREVER ) and provides the between(Temporal, Temporal) utility method: LocalDate d1 = LocalDate.of(2026, Month.JANUARY, 1);
LocalDate d2 = LocalDate.of(2026, Month.JANUARY, 15);
- long daysBetween = ChronoUnit.DAYS.between(d1, d2); // 14 (d1 inclusive, d2 exclusive)
- Key Rules for ChronoUnit.between()
Truncation to Whole Units : between() calculates the number of complete whole units . Any fractional remainder is truncated. For example, between 10:00 and 11:45, ChronoUnit.HOURS.between() yields 1 .
Direction and Sign : The calculation is temporal2Exclusive - temporal1Inclusive . If the second argument is chronologically earlier than the first, the result is negative : LocalTime t1 = LocalTime.of(15, 0);
- LocalTime t2 = LocalTime.of(12, 0);
- long hours = ChronoUnit.HOURS.between(t1, t2); // -3
Unit Compatibility : Attempting to calculate an unsupported unit (such as hours between two LocalDate instances) throws UnsupportedTemporalTypeException : // COMPILES! But throws UnsupportedTemporalTypeException at runtime: