RFR: 8368856: Add methods for saturating Duration arithmetic to Instant [v7]

Pavel Rappo prappo at openjdk.org
Wed Oct 8 21:54:06 UTC 2025


On Wed, 8 Oct 2025 20:03:37 GMT, Roger Riggs <rriggs at openjdk.org> wrote:

>> It sure can be generalised like you said. The question is how useful that would be as far as the main use case is concerned.
>> 
>> Also, `java.time` is a kind of API that makes it hard to tell if a particular call would work unless you know the exact types of the receiver and the arguments. Having a method that throws an exception for everything but one particular type of the receiver and the argument -- even if temporarily -- can be confusing. (I've done my fair share of attempts to add a `Period` to an `Instant`.) But we can try, experiment, and see what happens.
>
> A Period with only day units *can* be added to an Instant.  (Because the day can be converted to seconds).
> 
> jshell> import java.time.*
> jshell> var i = Instant.now()
> i ==> 2025-10-08T20:02:15.231622Z
> jshell> var p = Period.of(0,0,1)
> p ==> P1D
> jshell> i.plus(p)
> $4 ==> 2025-10-09T20:02:15.231622Z

You are right: if a `Period` is carefully picked, it can be added to `Instant`. However, one cannot _always_ convert days to seconds. For example,


jshell> Duration.from(Period.ofDays(1))
|  Exception java.time.temporal.UnsupportedTemporalTypeException: Unit must not have an estimated duration
|        at Duration.plus (Duration.java:733)
|        at Duration.from (Duration.java:340)
|        at (#23:1)


If you ask me, that feels surprising.

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/27549#discussion_r2415109640


More information about the core-libs-dev mailing list