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

前端 未结 5 1979
醉话见心
醉话见心 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:54

    If you look at the code for plus(long, TemporalUnit) , it does not support WEEK,

     @Override
         public Instant plus(long amountToAdd, TemporalUnit unit) {
             if (unit instanceof ChronoUnit) {
                 switch ((ChronoUnit) unit) {
                     case NANOS: return plusNanos(amountToAdd);
                     case MICROS: return plus(amountToAdd / 1000_000, (amountToAdd % 1000_000) * 1000);
                     case MILLIS: return plusMillis(amountToAdd);
                     case SECONDS: return plusSeconds(amountToAdd);
                     case MINUTES: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_MINUTE));
                     case HOURS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_HOUR));
                     case HALF_DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY / 2));
                     case DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY));
                 }
                 throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
             }
             return unit.addTo(this, amountToAdd);
         }
    

    From code it is clear that results are calculated by multiplying seconds representation of units, a Week/Month/year can not be logically and consistently represented by seconds as these are not universal contants according to javadoc.

提交回复
热议问题