1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * Copyright (c) 2011-2012, Stephen Colebourne & Michael Nascimento Santos
  28  *
  29  * All rights reserved.
  30  *
  31  * Redistribution and use in source and binary forms, with or without
  32  * modification, are permitted provided that the following conditions are met:
  33  *
  34  *  * Redistributions of source code must retain the above copyright notice,
  35  *    this list of conditions and the following disclaimer.
  36  *
  37  *  * Redistributions in binary form must reproduce the above copyright notice,
  38  *    this list of conditions and the following disclaimer in the documentation
  39  *    and/or other materials provided with the distribution.
  40  *
  41  *  * Neither the name of JSR-310 nor the names of its contributors
  42  *    may be used to endorse or promote products derived from this software
  43  *    without specific prior written permission.
  44  *
  45  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  46  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  47  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  48  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  49  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  50  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  51  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  52  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  53  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  54  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  55  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  56  */
  57 package java.time.temporal;
  58 
  59 import static java.time.DayOfWeek.THURSDAY;
  60 import static java.time.DayOfWeek.WEDNESDAY;
  61 import static java.time.temporal.ChronoField.DAY_OF_WEEK;
  62 import static java.time.temporal.ChronoField.DAY_OF_YEAR;
  63 import static java.time.temporal.ChronoField.EPOCH_DAY;
  64 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  65 import static java.time.temporal.ChronoField.YEAR;
  66 import static java.time.temporal.ChronoUnit.DAYS;
  67 import static java.time.temporal.ChronoUnit.FOREVER;
  68 import static java.time.temporal.ChronoUnit.MONTHS;
  69 import static java.time.temporal.ChronoUnit.WEEKS;
  70 import static java.time.temporal.ChronoUnit.YEARS;
  71 
  72 import java.time.DateTimeException;
  73 import java.time.Duration;
  74 import java.time.LocalDate;
  75 import java.time.chrono.Chronology;
  76 import java.time.chrono.IsoChronology;
  77 import java.util.HashMap;
  78 import java.util.Map;
  79 
  80 /**
  81  * Fields and units specific to the ISO-8601 calendar system,
  82  * including quarter-of-year and week-based-year.
  83  * <p>
  84  * This class defines fields and units that are specific to the ISO calendar system.
  85  *
  86  * <h3>Quarter of year</h3>
  87  * The ISO-8601 standard is based on the standard civic 12 month year.
  88  * This is commonly divided into four quarters, often abbreviated as Q1, Q2, Q3 and Q4.
  89  * <p>
  90  * January, February and March are in Q1.
  91  * April, May and June are in Q2.
  92  * July, August and September are in Q3.
  93  * October, November and December are in Q4.
  94  * <p>
  95  * The complete date is expressed using three fields:
  96  * <p><ul>
  97  * <li>{@link #DAY_OF_QUARTER DAY_OF_QUARTER} - the day within the quarter, from 1 to 90, 91 or 92
  98  * <li>{@link #QUARTER_OF_YEAR QUARTER_OF_YEAR} - the week within the week-based-year
  99  * <li>{@link ChronoField#YEAR YEAR} - the standard ISO year
 100  * </ul><p>
 101  *
 102  * <h3>Week based years</h3>
 103  * The ISO-8601 standard was originally intended as a data interchange format,
 104  * defining a string format for dates and times. However, it also defines an
 105  * alternate way of expressing the date, based on the concept of week-based-year.
 106  * <p>
 107  * The date is expressed using three fields:
 108  * <p><ul>
 109  * <li>{@link ChronoField#DAY_OF_WEEK DAY_OF_WEEK} - the standard field defining the
 110  *  day-of-week from Monday (1) to Sunday (7)
 111  * <li>{@link #WEEK_OF_WEEK_BASED_YEAR} - the week within the week-based-year
 112  * <li>{@link #WEEK_BASED_YEAR WEEK_BASED_YEAR} - the week-based-year
 113  * </ul><p>
 114  * The week-based-year itself is defined relative to the standard ISO proleptic year.
 115  * It differs from the standard year in that it always starts on a Monday.
 116  * <p>
 117  * The first week of a week-based-year is the first Monday-based week of the standard
 118  * ISO year that has at least 4 days in the new year.
 119  * <p><ul>
 120  * <li>If January 1st is Monday then week 1 starts on January 1st
 121  * <li>If January 1st is Tuesday then week 1 starts on December 31st of the previous standard year
 122  * <li>If January 1st is Wednesday then week 1 starts on December 30th of the previous standard year
 123  * <li>If January 1st is Thursday then week 1 starts on December 29th of the previous standard year
 124  * <li>If January 1st is Friday then week 1 starts on January 4th
 125  * <li>If January 1st is Saturday then week 1 starts on January 3rd
 126  * <li>If January 1st is Sunday then week 1 starts on January 2nd
 127  * </ul><p>
 128  * There are 52 weeks in most week-based years, however on occasion there are 53 weeks.
 129  * <p>
 130  * For example:
 131  * <p>
 132  * <table cellpadding="0" cellspacing="3" border="0" style="text-align: left; width: 50%;">
 133  * <caption>Examples of Week based Years</caption>
 134  * <tr><th>Date</th><th>Day-of-week</th><th>Field values</th></tr>
 135  * <tr><th>2008-12-28</th><td>Sunday</td><td>Week 52 of week-based-year 2008</td></tr>
 136  * <tr><th>2008-12-29</th><td>Monday</td><td>Week 1 of week-based-year 2009</td></tr>
 137  * <tr><th>2008-12-31</th><td>Wednesday</td><td>Week 1 of week-based-year 2009</td></tr>
 138  * <tr><th>2009-01-01</th><td>Thursday</td><td>Week 1 of week-based-year 2009</td></tr>
 139  * <tr><th>2009-01-04</th><td>Sunday</td><td>Week 1 of week-based-year 2009</td></tr>
 140  * <tr><th>2009-01-05</th><td>Monday</td><td>Week 2 of week-based-year 2009</td></tr>
 141  * </table>
 142  *
 143  * <h3>Specification for implementors</h3>
 144  * <p>
 145  * This class is immutable and thread-safe.
 146  *
 147  * @since 1.8
 148  */
 149 public final class IsoFields {
 150 
 151     /**
 152      * The field that represents the day-of-quarter.
 153      * <p>
 154      * This field allows the day-of-quarter value to be queried and set.
 155      * The day-of-quarter has values from 1 to 90 in Q1 of a standard year, from 1 to 91
 156      * in Q1 of a leap year, from 1 to 91 in Q2 and from 1 to 92 in Q3 and Q4.
 157      * <p>
 158      * The day-of-quarter can only be calculated if the day-of-year, month-of-year and year
 159      * are available.
 160      * <p>
 161      * When setting this field, the value is allowed to be partially lenient, taking any
 162      * value from 1 to 92. If the quarter has less than 92 days, then day 92, and
 163      * potentially day 91, is in the following quarter.
 164      * <p>
 165      * This unit is an immutable and thread-safe singleton.
 166      */
 167     public static final TemporalField DAY_OF_QUARTER = Field.DAY_OF_QUARTER;
 168     /**
 169      * The field that represents the quarter-of-year.
 170      * <p>
 171      * This field allows the quarter-of-year value to be queried and set.
 172      * The quarter-of-year has values from 1 to 4.
 173      * <p>
 174      * The day-of-quarter can only be calculated if the month-of-year is available.
 175      * <p>
 176      * This unit is an immutable and thread-safe singleton.
 177      */
 178     public static final TemporalField QUARTER_OF_YEAR = Field.QUARTER_OF_YEAR;
 179     /**
 180      * The field that represents the week-of-week-based-year.
 181      * <p>
 182      * This field allows the week of the week-based-year value to be queried and set.
 183      * <p>
 184      * This unit is an immutable and thread-safe singleton.
 185      */
 186     public static final TemporalField WEEK_OF_WEEK_BASED_YEAR = Field.WEEK_OF_WEEK_BASED_YEAR;
 187     /**
 188      * The field that represents the week-based-year.
 189      * <p>
 190      * This field allows the week-based-year value to be queried and set.
 191      * <p>
 192      * This unit is an immutable and thread-safe singleton.
 193      */
 194     public static final TemporalField WEEK_BASED_YEAR = Field.WEEK_BASED_YEAR;
 195     /**
 196      * The unit that represents week-based-years for the purpose of addition and subtraction.
 197      * <p>
 198      * This allows a number of week-based-years to be added to, or subtracted from, a date.
 199      * The unit is equal to either 52 or 53 weeks.
 200      * The estimated duration of a week-based-year is the same as that of a standard ISO
 201      * year at {@code 365.2425 Days}.
 202      * <p>
 203      * The rules for addition add the number of week-based-years to the existing value
 204      * for the week-based-year field. If the resulting week-based-year only has 52 weeks,
 205      * then the date will be in week 1 of the following week-based-year.
 206      * <p>
 207      * This unit is an immutable and thread-safe singleton.
 208      */
 209     public static final TemporalUnit WEEK_BASED_YEARS = Unit.WEEK_BASED_YEARS;
 210     /**
 211      * Unit that represents the concept of a quarter-year.
 212      * For the ISO calendar system, it is equal to 3 months.
 213      * The estimated duration of a quarter-year is one quarter of {@code 365.2425 Days}.
 214      * <p>
 215      * This unit is an immutable and thread-safe singleton.
 216      */
 217     public static final TemporalUnit QUARTER_YEARS = Unit.QUARTER_YEARS;
 218 
 219     /**
 220      * Restricted constructor.
 221      */
 222     private IsoFields() {
 223         throw new AssertionError("Not instantiable");
 224     }
 225 
 226     //-----------------------------------------------------------------------
 227     /**
 228      * Implementation of the field.
 229      */
 230     private static enum Field implements TemporalField {
 231         DAY_OF_QUARTER {
 232             @Override
 233             public String getName() {
 234                 return "DayOfQuarter";
 235             }
 236             @Override
 237             public TemporalUnit getBaseUnit() {
 238                 return DAYS;
 239             }
 240             @Override
 241             public TemporalUnit getRangeUnit() {
 242                 return QUARTER_YEARS;
 243             }
 244             @Override
 245             public ValueRange range() {
 246                 return ValueRange.of(1, 90, 92);
 247             }
 248             @Override
 249             public boolean isSupportedBy(TemporalAccessor temporal) {
 250                 return temporal.isSupported(DAY_OF_YEAR) && temporal.isSupported(MONTH_OF_YEAR) &&
 251                         temporal.isSupported(YEAR) && isIso(temporal);
 252             }
 253             @Override
 254             public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
 255                 if (isSupportedBy(temporal) == false) {
 256                     throw new DateTimeException("Unsupported field: DayOfQuarter");
 257                 }
 258                 long qoy = temporal.getLong(QUARTER_OF_YEAR);
 259                 if (qoy == 1) {
 260                     long year = temporal.getLong(YEAR);
 261                     return (IsoChronology.INSTANCE.isLeapYear(year) ? ValueRange.of(1, 91) : ValueRange.of(1, 90));
 262                 } else if (qoy == 2) {
 263                     return ValueRange.of(1, 91);
 264                 } else if (qoy == 3 || qoy == 4) {
 265                     return ValueRange.of(1, 92);
 266                 } // else value not from 1 to 4, so drop through
 267                 return range();
 268             }
 269             @Override
 270             public long getFrom(TemporalAccessor temporal) {
 271                 if (isSupportedBy(temporal) == false) {
 272                     throw new DateTimeException("Unsupported field: DayOfQuarter");
 273                 }
 274                 int doy = temporal.get(DAY_OF_YEAR);
 275                 int moy = temporal.get(MONTH_OF_YEAR);
 276                 long year = temporal.getLong(YEAR);
 277                 return doy - QUARTER_DAYS[((moy - 1) / 3) + (IsoChronology.INSTANCE.isLeapYear(year) ? 4 : 0)];
 278             }
 279             @SuppressWarnings("unchecked")
 280             @Override
 281             public <R extends Temporal> R adjustInto(R temporal, long newValue) {
 282                 // calls getFrom() to check if supported
 283                 long curValue = getFrom(temporal);
 284                 range().checkValidValue(newValue, this);  // leniently check from 1 to 92 TODO: check
 285                 return (R) temporal.with(DAY_OF_YEAR, temporal.getLong(DAY_OF_YEAR) + (newValue - curValue));
 286             }
 287             @Override
 288             public Map<TemporalField, Long> resolve(TemporalAccessor temporal, long value) {
 289                 if ((temporal.isSupported(YEAR) && temporal.isSupported(DAY_OF_QUARTER)) == false) {
 290                     return null;
 291                 }
 292                 int y = temporal.get(YEAR);
 293                 int qoy = temporal.get(QUARTER_OF_YEAR);
 294                 range().checkValidValue(value, this);  // leniently check from 1 to 92 TODO: check
 295                 LocalDate date = LocalDate.of(y, ((qoy - 1) * 3) + 1, 1).plusDays(value - 1);
 296                 Map<TemporalField, Long> result = new HashMap<>(4, 1.0f);
 297                 result.put(EPOCH_DAY, date.toEpochDay());
 298                 result.put(YEAR, null);
 299                 result.put(QUARTER_OF_YEAR, null);
 300                 return result;
 301             }
 302         },
 303         QUARTER_OF_YEAR {
 304             @Override
 305             public String getName() {
 306                 return "QuarterOfYear";
 307             }
 308             @Override
 309             public TemporalUnit getBaseUnit() {
 310                 return QUARTER_YEARS;
 311             }
 312             @Override
 313             public TemporalUnit getRangeUnit() {
 314                 return YEARS;
 315             }
 316             @Override
 317             public ValueRange range() {
 318                 return ValueRange.of(1, 4);
 319             }
 320             @Override
 321             public boolean isSupportedBy(TemporalAccessor temporal) {
 322                 return temporal.isSupported(MONTH_OF_YEAR) && isIso(temporal);
 323             }
 324             @Override
 325             public long getFrom(TemporalAccessor temporal) {
 326                 if (isSupportedBy(temporal) == false) {
 327                     throw new DateTimeException("Unsupported field: QuarterOfYear");
 328                 }
 329                 long moy = temporal.getLong(MONTH_OF_YEAR);
 330                 return ((moy + 2) / 3);
 331             }
 332             @SuppressWarnings("unchecked")
 333             @Override
 334             public <R extends Temporal> R adjustInto(R temporal, long newValue) {
 335                 // calls getFrom() to check if supported
 336                 long curValue = getFrom(temporal);
 337                 range().checkValidValue(newValue, this);  // strictly check from 1 to 4
 338                 return (R) temporal.with(MONTH_OF_YEAR, temporal.getLong(MONTH_OF_YEAR) + (newValue - curValue) * 3);
 339             }
 340         },
 341         WEEK_OF_WEEK_BASED_YEAR {
 342             @Override
 343             public String getName() {
 344                 return "WeekOfWeekBasedYear";
 345             }
 346             @Override
 347             public TemporalUnit getBaseUnit() {
 348                 return WEEKS;
 349             }
 350             @Override
 351             public TemporalUnit getRangeUnit() {
 352                 return WEEK_BASED_YEARS;
 353             }
 354             @Override
 355             public ValueRange range() {
 356                 return ValueRange.of(1, 52, 53);
 357             }
 358             @Override
 359             public boolean isSupportedBy(TemporalAccessor temporal) {
 360                 return temporal.isSupported(EPOCH_DAY) && isIso(temporal);
 361             }
 362             @Override
 363             public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
 364                 if (isSupportedBy(temporal) == false) {
 365                     throw new DateTimeException("Unsupported field: WeekOfWeekBasedYear");
 366                 }
 367                 return getWeekRange(LocalDate.from(temporal));
 368             }
 369             @Override
 370             public long getFrom(TemporalAccessor temporal) {
 371                 if (isSupportedBy(temporal) == false) {
 372                     throw new DateTimeException("Unsupported field: WeekOfWeekBasedYear");
 373                 }
 374                 return getWeek(LocalDate.from(temporal));
 375             }
 376             @SuppressWarnings("unchecked")
 377             @Override
 378             public <R extends Temporal> R adjustInto(R temporal, long newValue) {
 379                 // calls getFrom() to check if supported
 380                 range().checkValidValue(newValue, this);  // lenient range
 381                 return (R) temporal.plus(Math.subtractExact(newValue, getFrom(temporal)), WEEKS);
 382             }
 383             @Override
 384             public Map<TemporalField, Long> resolve(TemporalAccessor temporal, long value) {
 385                 if ((temporal.isSupported(WEEK_BASED_YEAR) && temporal.isSupported(DAY_OF_WEEK)) == false) {
 386                     return null;
 387                 }
 388                 int wby = temporal.get(WEEK_BASED_YEAR);
 389                 int dow = temporal.get(DAY_OF_WEEK);
 390                 range().checkValidValue(value, this);  // lenient range
 391                 LocalDate date = LocalDate.of(wby, 1, 4).plusWeeks(value - 1).with(DAY_OF_WEEK, dow);
 392                 Map<TemporalField, Long> result = new HashMap<>(2, 1.0f);
 393                 result.put(EPOCH_DAY, date.toEpochDay());
 394                 result.put(WEEK_BASED_YEAR, null);
 395                 result.put(DAY_OF_WEEK, null);
 396                 return result;
 397             }
 398         },
 399         WEEK_BASED_YEAR {
 400             @Override
 401             public String getName() {
 402                 return "WeekBasedYear";
 403             }
 404             @Override
 405             public TemporalUnit getBaseUnit() {
 406                 return WEEK_BASED_YEARS;
 407             }
 408             @Override
 409             public TemporalUnit getRangeUnit() {
 410                 return FOREVER;
 411             }
 412             @Override
 413             public ValueRange range() {
 414                 return YEAR.range();
 415             }
 416             @Override
 417             public boolean isSupportedBy(TemporalAccessor temporal) {
 418                 return temporal.isSupported(EPOCH_DAY) && isIso(temporal);
 419             }
 420             @Override
 421             public long getFrom(TemporalAccessor temporal) {
 422                 if (isSupportedBy(temporal) == false) {
 423                     throw new DateTimeException("Unsupported field: WeekBasedYear");
 424                 }
 425                 return getWeekBasedYear(LocalDate.from(temporal));
 426             }
 427             @SuppressWarnings("unchecked")
 428             @Override
 429             public <R extends Temporal> R adjustInto(R temporal, long newValue) {
 430                 if (isSupportedBy(temporal) == false) {
 431                     throw new DateTimeException("Unsupported field: WeekBasedYear");
 432                 }
 433                 int newVal = range().checkValidIntValue(newValue, WEEK_BASED_YEAR);  // strict check
 434                 LocalDate date = LocalDate.from(temporal);
 435                 int week = getWeek(date);
 436                 date = date.withDayOfYear(180).withYear(newVal).with(WEEK_OF_WEEK_BASED_YEAR, week);
 437                 return (R) date.with(date);
 438             }
 439         };
 440 
 441         @Override
 442         public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
 443             return range();
 444         }
 445 
 446         @Override
 447         public String toString() {
 448             return getName();
 449         }
 450 
 451         //-------------------------------------------------------------------------
 452         private static final int[] QUARTER_DAYS = {0, 90, 181, 273, 0, 91, 182, 274};
 453 
 454         private static boolean isIso(TemporalAccessor temporal) {
 455             return Chronology.from(temporal).equals(IsoChronology.INSTANCE);
 456         }
 457 
 458         private static ValueRange getWeekRange(LocalDate date) {
 459             int wby = getWeekBasedYear(date);
 460             date = date.withDayOfYear(1).withYear(wby);
 461             // 53 weeks if standard year starts on Thursday, or Wed in a leap year
 462             if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {
 463                 return ValueRange.of(1, 53);
 464             }
 465             return ValueRange.of(1, 52);
 466         }
 467 
 468         private static int getWeek(LocalDate date) {
 469             int dow0 = date.getDayOfWeek().ordinal();
 470             int doy0 = date.getDayOfYear() - 1;
 471             int doyThu0 = doy0 + (3 - dow0);  // adjust to mid-week Thursday (which is 3 indexed from zero)
 472             int alignedWeek = doyThu0 / 7;
 473             int firstThuDoy0 = doyThu0 - (alignedWeek * 7);
 474             int firstMonDoy0 = firstThuDoy0 - 3;
 475             if (firstMonDoy0 < -3) {
 476                 firstMonDoy0 += 7;
 477             }
 478             if (doy0 < firstMonDoy0) {
 479                 return (int) getWeekRange(date.withDayOfYear(180).minusYears(1)).getMaximum();
 480             }
 481             int week = ((doy0 - firstMonDoy0) / 7) + 1;
 482             if (week == 53) {
 483                 if ((firstMonDoy0 == -3 || (firstMonDoy0 == -2 && date.isLeapYear())) == false) {
 484                     week = 1;
 485                 }
 486             }
 487             return week;
 488         }
 489 
 490         private static int getWeekBasedYear(LocalDate date) {
 491             int year = date.getYear();
 492             int doy = date.getDayOfYear();
 493             if (doy <= 3) {
 494                 int dow = date.getDayOfWeek().ordinal();
 495                 if (doy - dow < -2) {
 496                     year--;
 497                 }
 498             } else if (doy >= 363) {
 499                 int dow = date.getDayOfWeek().ordinal();
 500                 doy = doy - 363 - (date.isLeapYear() ? 1 : 0);
 501                 if (doy - dow >= 0) {
 502                     year++;
 503                 }
 504             }
 505             return year;
 506         }
 507     }
 508 
 509     //-----------------------------------------------------------------------
 510     /**
 511      * Implementation of the period unit.
 512      */
 513     private static enum Unit implements TemporalUnit {
 514 
 515         /**
 516          * Unit that represents the concept of a week-based-year.
 517          */
 518         WEEK_BASED_YEARS("WeekBasedYears", Duration.ofSeconds(31556952L)),
 519         /**
 520          * Unit that represents the concept of a quarter-year.
 521          */
 522         QUARTER_YEARS("QuarterYears", Duration.ofSeconds(31556952L / 4));
 523 
 524         private final String name;
 525         private final Duration duration;
 526 
 527         private Unit(String name, Duration estimatedDuration) {
 528             this.name = name;
 529             this.duration = estimatedDuration;
 530         }
 531 
 532         @Override
 533         public String getName() {
 534             return name;
 535         }
 536 
 537         @Override
 538         public Duration getDuration() {
 539             return duration;
 540         }
 541 
 542         @Override
 543         public boolean isDurationEstimated() {
 544             return true;
 545         }
 546 
 547         @Override
 548         public boolean isSupportedBy(Temporal temporal) {
 549             return temporal.isSupported(EPOCH_DAY);
 550         }
 551 
 552         @SuppressWarnings("unchecked")
 553         @Override
 554         public <R extends Temporal> R addTo(R temporal, long amount) {
 555             switch(this) {
 556                 case WEEK_BASED_YEARS:
 557                     return (R) temporal.with(WEEK_BASED_YEAR,
 558                             Math.addExact(temporal.get(WEEK_BASED_YEAR), amount));
 559                 case QUARTER_YEARS:
 560                     // no overflow (256 is multiple of 4)
 561                     return (R) temporal.plus(amount / 256, YEARS)
 562                             .plus((amount % 256) * 3, MONTHS);
 563                 default:
 564                     throw new IllegalStateException("Unreachable");
 565             }
 566         }
 567 
 568         @Override
 569         public long between(Temporal temporal1, Temporal temporal2) {
 570             switch(this) {
 571                 case WEEK_BASED_YEARS:
 572                     return Math.subtractExact(temporal2.getLong(WEEK_BASED_YEAR),
 573                             temporal1.getLong(WEEK_BASED_YEAR));
 574                 case QUARTER_YEARS:
 575                     return temporal1.periodUntil(temporal2, MONTHS) / 3;
 576                 default:
 577                     throw new IllegalStateException("Unreachable");
 578             }
 579         }
 580 
 581         @Override
 582         public String toString() {
 583             return getName();
 584 
 585         }
 586     }
 587 }