Why is adding weeks to java.time.Instant not supported?

前端 未结 5 1973
醉话见心
醉话见心 2021-01-18 05:50

The following piece of code:

Instant inFourWeeks = Instant.now().plus(4L, ChronoUnit.WEEKS);

Throws an exception:

java.time         


        
5条回答
  •  太阳男子
    2021-01-18 05:59

    ChronoUnit.WEEKS may be used for weeks in other calendar systems than the ISO calendar. And such weeks may be for example 6 or 10 days long. So while it may be argued that it makes sense that Instant supports days, the same is not true for weeks.

    From the documentation:

    Unit that represents the concept of a week. For the ISO calendar system, it is equal to 7 days.

    When used with other calendar systems it must correspond to an integral number of days.

    It clearly follows from this that WEEKSdoes not generally assume the ISO calendar system and may be used with other calendars too.

    The other part of the argument is that Instant does not assume one calendar system but can be used with different calendar systems too. (By contrast, ZonedDateTime, for example, assumes the ISO-8601 calendar system so does support weeks.)

    PS I’d rather put the question the other way around: why does Instant support days? A day may be 23, 23.5, 24, 24.5 or 25 hours, and historically other durations too.

    Link: Documentation of ChronoUnit.WEEKS.

提交回复
热议问题