bhylu.com

Advertisements

Java Separate a Calendar Date from an Instant

A booking date, a local session time and an instant on a global timeline represent different facts. Select a java.time type that preserves the meaning you need.

Understand the idea

LocalDate has a calendar date without a time zone. LocalDateTime adds a local clock time but still does not identify an instant without a zone or offset. Instant represents a point on the UTC timeline. Time zones can have gaps and overlaps around clock changes. Use a Clock in code that needs the current time so tests can supply a fixed instant rather than relying on the actual day.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import java.time.*;

public class Main {
    public static void main(String[] args) {
        LocalDate opening = LocalDate.of(2026, 11, 3);
        System.out.println(opening.plusWeeks(2));
        Clock clock = Clock.fixed(Instant.parse("2026-11-03T08:00:00Z"), ZoneOffset.UTC);
        System.out.println(LocalDate.now(clock));
    }
}

Expected output

2026-11-17
2026-11-03

The date arithmetic returns another LocalDate and leaves opening unchanged. The fixed Clock gives the second calculation a repeatable today. This is a teaching fixture, not a claim about when a lesson was published. For user-facing times, store the relevant zone rather than treating the server’s default zone as a global rule.

Check the official Java documentation for detailed contracts and supported options.