Java › Java Date & Time API (java.time)
How does the Instant class represent a point in time, and how does it differ fundamentally from ZonedDateTime in terms of what it actually represents and how it should be used?
AdvancedAnswer
Instant represents a single, unambiguous point on the timeline measured as elapsed time since the epoch (1970-01-01T00:00:00Z), stored internally with nanosecond precision, entirely independent of any timezone or human-readable calendar representation -- it's the appropriate choice for timestamping events (like a log entry's creation time, or a database record's last-modified timestamp) where you need an unambiguous, machine-comparable moment in time without caring about how a human would read it in their local calendar; ZonedDateTime, by contrast, is specifically for representing and DISPLAYING a date-time in a particular timezone's local calendar convention, converting an Instant's underlying universal moment into a human-meaningful year/month/day/hour/minute representation for a specific place.
Instant now = Instant.now(); // pure timestamp, e.g. 2024-06-01T18:30:00Z, no calendar/timezone concept
System.out.println(now);
// Convert to a human-readable local representation for a SPECIFIC timezone when needed for display
ZonedDateTime nyTime = now.atZone(ZoneId.of("America/New_York"));
ZonedDateTime tokyoTime = now.atZone(ZoneId.of("Asia/Tokyo"));
// Both represent the EXACT SAME underlying instant, just displayed differently for each timezoneReal-world example A distributed logging system timestamps every log entry using Instant (a pure, unambiguous, universally comparable moment), only converting to a ZonedDateTime for a specific timezone at the point of DISPLAYING logs to a user in their local dashboard, correctly separating the underlying data model (Instant) from its presentation (ZonedDateTime).