RFR: 8368856: Add methods for saturating Duration arithmetic to Instant [v7]
Roger Riggs
rriggs at openjdk.org
Thu Oct 9 14:18:05 UTC 2025
On Wed, 8 Oct 2025 21:50:55 GMT, Pavel Rappo <prappo at openjdk.org> wrote:
>> 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.
As specified and implemented, `Duration.plus(long amount, TemporalUnit)` does not make an exception for amount == 0. For any other value of month or years, the value is an estimate and the exception is thrown.
It might be useful to consider a change (as a separate enhancement)
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/27549#discussion_r2416958704
More information about the core-libs-dev
mailing list