Date & Time API
Instant
Represent a specific point on the timeline with nanosecond precision.
Interview: Commonly tested on Instant timestamps, epoch seconds, and comparing instants.
An Instant represents a single point on the timeline, measured in nanoseconds relative to the Unix Epoch of Jan 1, 1970 UTC.
Core Idea
Instant models a UTC timestamp, independent of local timezone perspectives.
Why It Matters
Essential for database audit logging (e.g. created_at timestamp) to ensure consistent records.
Interview Lens
Tests how to convert between Instant, EpochMillis, and ZonedDateTime.
Core API Operations
- Creation:
Instant.now()orInstant.ofEpochMilli(timestamp). - Comparisons:
isBefore(),isAfter(). - Conversion: Convert to zoned time by applying a zone:
instant.atZone(ZoneId).
Code Walkthrough
This program shows how to capture timestamps and convert them back to local times.
import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime;public class InstantDemo { public static void main(String[] args) { Instant now = Instant.now(); System.out.println("Current Instant: " + now); // Prints in UTC format (e.g. Z suffix)
// Convert to local millisecond timestamp long epochMilli = now.toEpochMilli(); System.out.println("Epoch Milliseconds: " + epochMilli);
// Convert back to ZonedDateTime ZonedDateTime localTime = now.atZone(ZoneId.systemDefault()); System.out.println("System Zoned Time: " + localTime); } }
Interview-Relevant Information
Q: How do you measure execution elapsed time using Instant?
Answer: Capture a start instant, an end instant, and then use Duration.between(start, end) to calculate the elapsed time.
Quick Checklist
What timezone is Instant representation based on? How do you get millisecond timestamps? If yes, you understand Instant.
Use Cases
Recording creation and update audit timestamps in database tables.
Logging message dispatch timestamps in distributed messaging systems.
Common Mistakes
Assuming Instant has local timezone context (it always represents a point in time in UTC).
Calling toString() on Instant and expecting local system formatting (it always prints ISO-8601 UTC format).