Instant Arithmetic: plus(), minus(), and Temporal Units
What you'll learn: How to add or subtract time durations from an Instant using methods like plusSeconds(), minusMillis(), and Duration objects.
The Core Idea
Once you have an Instant representing a point in time, you'll often need to calculate new instants relative to it—like "3 hours from now" or "500 milliseconds ago." Java's Instant class provides arithmetic methods that let you add or subtract time units without manual epoch calculations.
Basic Arithmetic Methods
The Instant class offers granular methods for common time units:
Instant now = Instant.now();
Instant later = now.plusSeconds(3600); // 1 hour later
Instant earlier = now.minusMillis(500); // 500ms earlier
Instant muchLater = now.plusSeconds(86400); // 1 day later
Each method returns a new Instant—the original is immutable.
Working with Duration Objects
For more complex durations, you can use Duration objects with the generic plus() and minus() methods:
Instant start = Instant.ofEpochSecond(1000000000L);
Duration fiveMinutes = Duration.ofMinutes(5);
Instant end = start.plus(fiveMinutes);
Duration twoHours = Duration.ofHours(2);
Instant past = start.minus(twoHours);
This approach is cleaner when dealing with compound durations or values calculated elsewhere.
Think of It Like a Calculator
Imagine Instant as a timestamp on a number line. The plus() and minus() methods slide you forward or backward along that line by specific amounts—whether you're moving by seconds, milliseconds, or more complex durations.
Key Takeaway: Use plusSeconds(), minusMillis(), and similar methods for simple arithmetic on Instant values, or use plus(Duration) and minus(Duration) for more flexible time calculations—all operations return new immutable Instant objects.