1 /*
   2  * Copyright (c) 2012, 2016, 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.ChronoLocalDate;
  76 import java.time.chrono.Chronology;
  77 import java.time.chrono.IsoChronology;
  78 import java.time.format.ResolverStyle;
  79 import java.util.Locale;
  80 import java.util.Map;
  81 import java.util.Objects;
  82 import java.util.ResourceBundle;
  83 
  84 import sun.util.locale.provider.LocaleProviderAdapter;
  85 import sun.util.locale.provider.LocaleResources;
  86 
  87 /**
  88  * Fields and units specific to the ISO-8601 calendar system,
  89  * including quarter-of-year and week-based-year.
  90  * <p>
  91  * This class defines fields and units that are specific to the ISO calendar system.
  92  *
  93  * <h3>Quarter of year</h3>
  94  * The ISO-8601 standard is based on the standard civic 12 month year.
  95  * This is commonly divided into four quarters, often abbreviated as Q1, Q2, Q3 and Q4.
  96  * <p>
  97  * January, February and March are in Q1.
  98  * April, May and June are in Q2.
  99  * July, August and September are in Q3.
 100  * October, November and December are in Q4.
 101  * <p>
 102  * The complete date is expressed using three fields:
 103  * <ul>
 104  * <li>{@link #DAY_OF_QUARTER DAY_OF_QUARTER} - the day within the quarter, from 1 to 90, 91 or 92
 105  * <li>{@link #QUARTER_OF_YEAR QUARTER_OF_YEAR} - the quarter within the year, from 1 to 4
 106  * <li>{@link ChronoField#YEAR YEAR} - the standard ISO year
 107  * </ul>
 108  *
 109  * <h3>Week based years</h3>
 110  * The ISO-8601 standard was originally intended as a data interchange format,
 111  * defining a string format for dates and times. However, it also defines an
 112  * alternate way of expressing the date, based on the concept of week-based-year.
 113  * <p>
 114  * The date is expressed using three fields:
 115  * <ul>
 116  * <li>{@link ChronoField#DAY_OF_WEEK DAY_OF_WEEK} - the standard field defining the
 117  *  day-of-week from Monday (1) to Sunday (7)
 118  * <li>{@link #WEEK_OF_WEEK_BASED_YEAR} - the week within the week-based-year
 119  * <li>{@link #WEEK_BASED_YEAR WEEK_BASED_YEAR} - the week-based-year
 120  * </ul>
 121  * The week-based-year itself is defined relative to the standard ISO proleptic year.
 122  * It differs from the standard year in that it always starts on a Monday.
 123  * <p>
 124  * The first week of a week-based-year is the first Monday-based week of the standard
 125  * ISO year that has at least 4 days in the new year.
 126  * <ul>
 127  * <li>If January 1st is Monday then week 1 starts on January 1st
 128  * <li>If January 1st is Tuesday then week 1 starts on December 31st of the previous standard year
 129  * <li>If January 1st is Wednesday then week 1 starts on December 30th of the previous standard year
 130  * <li>If January 1st is Thursday then week 1 starts on December 29th of the previous standard year
 131  * <li>If January 1st is Friday then week 1 starts on January 4th
 132  * <li>If January 1st is Saturday then week 1 starts on January 3rd
 133  * <li>If January 1st is Sunday then week 1 starts on January 2nd
 134  * </ul>
 135  * There are 52 weeks in most week-based years, however on occasion there are 53 weeks.
 136  * <p>
 137  * For example:
 138  *
 139  * <table cellpadding="0" cellspacing="3" border="0" style="text-align: left; width: 50%;">
 140  * <caption>Examples of Week based Years</caption>
 141  * <tr><th>Date</th><th>Day-of-week</th><th>Field values</th></tr>
 142  * <tr><th>2008-12-28</th><td>Sunday</td><td>Week 52 of week-based-year 2008</td></tr>
 143  * <tr><th>2008-12-29</th><td>Monday</td><td>Week 1 of week-based-year 2009</td></tr>
 144  * <tr><th>2008-12-31</th><td>Wednesday</td><td>Week 1 of week-based-year 2009</td></tr>
 145  * <tr><th>2009-01-01</th><td>Thursday</td><td>Week 1 of week-based-year 2009</td></tr>
 146  * <tr><th>2009-01-04</th><td>Sunday</td><td>Week 1 of week-based-year 2009</td></tr>
 147  * <tr><th>2009-01-05</th><td>Monday</td><td>Week 2 of week-based-year 2009</td></tr>
 148  * </table>
 149  *
 150  * @implSpec
 151  * <p>
 152  * This class is immutable and thread-safe.
 153  *
 154  * @since 1.8
 155  */
 156 public final class IsoFields {
 157 
 158     /**
 159      * The field that represents the day-of-quarter.
 160      * <p>
 161      * This field allows the day-of-quarter value to be queried and set.
 162      * The day-of-quarter has values from 1 to 90 in Q1 of a standard year, from 1 to 91
 163      * in Q1 of a leap year, from 1 to 91 in Q2 and from 1 to 92 in Q3 and Q4.
 164      * <p>
 165      * The day-of-quarter can only be calculated if the day-of-year, month-of-year and year
 166      * are available.
 167      * <p>
 168      * When setting this field, the value is allowed to be partially lenient, taking any
 169      * value from 1 to 92. If the quarter has less than 92 days, then day 92, and
 170      * potentially day 91, is in the following quarter.
 171      * <p>
 172      * In the resolving phase of parsing, a date can be created from a year,
 173      * quarter-of-year and day-of-quarter.
 174      * <p>
 175      * In {@linkplain ResolverStyle#STRICT strict mode}, all three fields are
 176      * validated against their range of valid values. The day-of-quarter field
 177      * is validated from 1 to 90, 91 or 92 depending on the year and quarter.
 178      * <p>
 179      * In {@linkplain ResolverStyle#SMART smart mode}, all three fields are
 180      * validated against their range of valid values. The day-of-quarter field is
 181      * validated between 1 and 92, ignoring the actual range based on the year and quarter.
 182      * If the day-of-quarter exceeds the actual range by one day, then the resulting date
 183      * is one day later. If the day-of-quarter exceeds the actual range by two days,
 184      * then the resulting date is two days later.
 185      * <p>
 186      * In {@linkplain ResolverStyle#LENIENT lenient mode}, only the year is validated
 187      * against the range of valid values. The resulting date is calculated equivalent to
 188      * the following three stage approach. First, create a date on the first of January
 189      * in the requested year. Then take the quarter-of-year, subtract one, and add the
 190      * amount in quarters to the date. Finally, take the day-of-quarter, subtract one,
 191      * and add the amount in days to the date.
 192      * <p>
 193      * This unit is an immutable and thread-safe singleton.
 194      */
 195     public static final TemporalField DAY_OF_QUARTER = Field.DAY_OF_QUARTER;
 196     /**
 197      * The field that represents the quarter-of-year.
 198      * <p>
 199      * This field allows the quarter-of-year value to be queried and set.
 200      * The quarter-of-year has values from 1 to 4.
 201      * <p>
 202      * The quarter-of-year can only be calculated if the month-of-year is available.
 203      * <p>
 204      * In the resolving phase of parsing, a date can be created from a year,
 205      * quarter-of-year and day-of-quarter.
 206      * See {@link #DAY_OF_QUARTER} for details.
 207      * <p>
 208      * This unit is an immutable and thread-safe singleton.
 209      */
 210     public static final TemporalField QUARTER_OF_YEAR = Field.QUARTER_OF_YEAR;
 211     /**
 212      * The field that represents the week-of-week-based-year.
 213      * <p>
 214      * This field allows the week of the week-based-year value to be queried and set.
 215      * The week-of-week-based-year has values from 1 to 52, or 53 if the
 216      * week-based-year has 53 weeks.
 217      * <p>
 218      * In the resolving phase of parsing, a date can be created from a
 219      * week-based-year, week-of-week-based-year and day-of-week.
 220      * <p>
 221      * In {@linkplain ResolverStyle#STRICT strict mode}, all three fields are
 222      * validated against their range of valid values. The week-of-week-based-year
 223      * field is validated from 1 to 52 or 53 depending on the week-based-year.
 224      * <p>
 225      * In {@linkplain ResolverStyle#SMART smart mode}, all three fields are
 226      * validated against their range of valid values. The week-of-week-based-year
 227      * field is validated between 1 and 53, ignoring the week-based-year.
 228      * If the week-of-week-based-year is 53, but the week-based-year only has
 229      * 52 weeks, then the resulting date is in week 1 of the following week-based-year.
 230      * <p>
 231      * In {@linkplain ResolverStyle#LENIENT lenient mode}, only the week-based-year
 232      * is validated against the range of valid values. If the day-of-week is outside
 233      * the range 1 to 7, then the resulting date is adjusted by a suitable number of
 234      * weeks to reduce the day-of-week to the range 1 to 7. If the week-of-week-based-year
 235      * value is outside the range 1 to 52, then any excess weeks are added or subtracted
 236      * from the resulting date.
 237      * <p>
 238      * This unit is an immutable and thread-safe singleton.
 239      */
 240     public static final TemporalField WEEK_OF_WEEK_BASED_YEAR = Field.WEEK_OF_WEEK_BASED_YEAR;
 241     /**
 242      * The field that represents the week-based-year.
 243      * <p>
 244      * This field allows the week-based-year value to be queried and set.
 245      * <p>
 246      * The field has a range that matches {@link LocalDate#MAX} and {@link LocalDate#MIN}.
 247      * <p>
 248      * In the resolving phase of parsing, a date can be created from a
 249      * week-based-year, week-of-week-based-year and day-of-week.
 250      * See {@link #WEEK_OF_WEEK_BASED_YEAR} for details.
 251      * <p>
 252      * This unit is an immutable and thread-safe singleton.
 253      */
 254     public static final TemporalField WEEK_BASED_YEAR = Field.WEEK_BASED_YEAR;
 255     /**
 256      * The unit that represents week-based-years for the purpose of addition and subtraction.
 257      * <p>
 258      * This allows a number of week-based-years to be added to, or subtracted from, a date.
 259      * The unit is equal to either 52 or 53 weeks.
 260      * The estimated duration of a week-based-year is the same as that of a standard ISO
 261      * year at {@code 365.2425 Days}.
 262      * <p>
 263      * The rules for addition add the number of week-based-years to the existing value
 264      * for the week-based-year field. If the resulting week-based-year only has 52 weeks,
 265      * then the date will be in week 1 of the following week-based-year.
 266      * <p>
 267      * This unit is an immutable and thread-safe singleton.
 268      */
 269     public static final TemporalUnit WEEK_BASED_YEARS = Unit.WEEK_BASED_YEARS;
 270     /**
 271      * Unit that represents the concept of a quarter-year.
 272      * For the ISO calendar system, it is equal to 3 months.
 273      * The estimated duration of a quarter-year is one quarter of {@code 365.2425 Days}.
 274      * <p>
 275      * This unit is an immutable and thread-safe singleton.
 276      */
 277     public static final TemporalUnit QUARTER_YEARS = Unit.QUARTER_YEARS;
 278 
 279     /**
 280      * Restricted constructor.
 281      */
 282     private IsoFields() {
 283         throw new AssertionError("Not instantiable");
 284     }
 285 
 286     //-----------------------------------------------------------------------
 287     /**
 288      * Implementation of the field.
 289      */
 290     private static enum Field implements TemporalField {
 291         DAY_OF_QUARTER {
 292             @Override
 293             public TemporalUnit getBaseUnit() {
 294                 return DAYS;
 295             }
 296             @Override
 297             public TemporalUnit getRangeUnit() {
 298                 return QUARTER_YEARS;
 299             }
 300             @Override
 301             public ValueRange range() {
 302                 return ValueRange.of(1, 90, 92);
 303             }
 304             @Override
 305             public boolean isSupportedBy(TemporalAccessor temporal) {
 306                 return temporal.isSupported(DAY_OF_YEAR) && temporal.isSupported(MONTH_OF_YEAR) &&
 307                         temporal.isSupported(YEAR) && isIso(temporal);
 308             }
 309             @Override
 310             public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
 311                 if (isSupportedBy(temporal) == false) {
 312                     throw new UnsupportedTemporalTypeException("Unsupported field: DayOfQuarter");
 313                 }
 314                 long qoy = temporal.getLong(QUARTER_OF_YEAR);
 315                 if (qoy == 1) {
 316                     long year = temporal.getLong(YEAR);
 317                     return (IsoChronology.INSTANCE.isLeapYear(year) ? ValueRange.of(1, 91) : ValueRange.of(1, 90));
 318                 } else if (qoy == 2) {
 319                     return ValueRange.of(1, 91);
 320                 } else if (qoy == 3 || qoy == 4) {
 321                     return ValueRange.of(1, 92);
 322                 } // else value not from 1 to 4, so drop through
 323                 return range();
 324             }
 325             @Override
 326             public long getFrom(TemporalAccessor temporal) {
 327                 if (isSupportedBy(temporal) == false) {
 328                     throw new UnsupportedTemporalTypeException("Unsupported field: DayOfQuarter");
 329                 }
 330                 int doy = temporal.get(DAY_OF_YEAR);
 331                 int moy = temporal.get(MONTH_OF_YEAR);
 332                 long year = temporal.getLong(YEAR);
 333                 return doy - QUARTER_DAYS[((moy - 1) / 3) + (IsoChronology.INSTANCE.isLeapYear(year) ? 4 : 0)];
 334             }
 335             @SuppressWarnings("unchecked")
 336             @Override
 337             public <R extends Temporal> R adjustInto(R temporal, long newValue) {
 338                 // calls getFrom() to check if supported
 339                 long curValue = getFrom(temporal);
 340                 range().checkValidValue(newValue, this);  // leniently check from 1 to 92 TODO: check
 341                 return (R) temporal.with(DAY_OF_YEAR, temporal.getLong(DAY_OF_YEAR) + (newValue - curValue));
 342             }
 343             @Override
 344             public ChronoLocalDate resolve(
 345                     Map<TemporalField, Long> fieldValues, TemporalAccessor partialTemporal, ResolverStyle resolverStyle) {
 346                 Long yearLong = fieldValues.get(YEAR);
 347                 Long qoyLong = fieldValues.get(QUARTER_OF_YEAR);
 348                 if (yearLong == null || qoyLong == null) {
 349                     return null;
 350                 }
 351                 int y = YEAR.checkValidIntValue(yearLong);  // always validate
 352                 long doq = fieldValues.get(DAY_OF_QUARTER);
 353                 ensureIso(partialTemporal);
 354                 LocalDate date;
 355                 if (resolverStyle == ResolverStyle.LENIENT) {
 356                     date = LocalDate.of(y, 1, 1).plusMonths(Math.multiplyExact(Math.subtractExact(qoyLong, 1), 3));
 357                     doq = Math.subtractExact(doq, 1);
 358                 } else {
 359                     int qoy = QUARTER_OF_YEAR.range().checkValidIntValue(qoyLong, QUARTER_OF_YEAR);  // validated
 360                     date = LocalDate.of(y, ((qoy - 1) * 3) + 1, 1);
 361                     if (doq < 1 || doq > 90) {
 362                         if (resolverStyle == ResolverStyle.STRICT) {
 363                             rangeRefinedBy(date).checkValidValue(doq, this);  // only allow exact range
 364                         } else {  // SMART
 365                             range().checkValidValue(doq, this);  // allow 1-92 rolling into next quarter
 366                         }
 367                     }
 368                     doq--;
 369                 }
 370                 fieldValues.remove(this);
 371                 fieldValues.remove(YEAR);
 372                 fieldValues.remove(QUARTER_OF_YEAR);
 373                 return date.plusDays(doq);
 374             }
 375             @Override
 376             public String toString() {
 377                 return "DayOfQuarter";
 378             }
 379         },
 380         QUARTER_OF_YEAR {
 381             @Override
 382             public TemporalUnit getBaseUnit() {
 383                 return QUARTER_YEARS;
 384             }
 385             @Override
 386             public TemporalUnit getRangeUnit() {
 387                 return YEARS;
 388             }
 389             @Override
 390             public ValueRange range() {
 391                 return ValueRange.of(1, 4);
 392             }
 393             @Override
 394             public boolean isSupportedBy(TemporalAccessor temporal) {
 395                 return temporal.isSupported(MONTH_OF_YEAR) && isIso(temporal);
 396             }
 397             @Override
 398             public long getFrom(TemporalAccessor temporal) {
 399                 if (isSupportedBy(temporal) == false) {
 400                     throw new UnsupportedTemporalTypeException("Unsupported field: QuarterOfYear");
 401                 }
 402                 long moy = temporal.getLong(MONTH_OF_YEAR);
 403                 return ((moy + 2) / 3);
 404             }
 405             public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
 406                 if (isSupportedBy(temporal) == false) {
 407                     throw new UnsupportedTemporalTypeException("Unsupported field: QuarterOfYear");
 408                 }
 409                 return super.rangeRefinedBy(temporal);
 410             }
 411             @SuppressWarnings("unchecked")
 412             @Override
 413             public <R extends Temporal> R adjustInto(R temporal, long newValue) {
 414                 // calls getFrom() to check if supported
 415                 long curValue = getFrom(temporal);
 416                 range().checkValidValue(newValue, this);  // strictly check from 1 to 4
 417                 return (R) temporal.with(MONTH_OF_YEAR, temporal.getLong(MONTH_OF_YEAR) + (newValue - curValue) * 3);
 418             }
 419             @Override
 420             public String toString() {
 421                 return "QuarterOfYear";
 422             }
 423         },
 424         WEEK_OF_WEEK_BASED_YEAR {
 425             @Override
 426             public String getDisplayName(Locale locale) {
 427                 Objects.requireNonNull(locale, "locale");
 428                 LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased()
 429                                             .getLocaleResources(locale);
 430                 ResourceBundle rb = lr.getJavaTimeFormatData();
 431                 return rb.containsKey("field.week") ? rb.getString("field.week") : toString();
 432             }
 433 
 434             @Override
 435             public TemporalUnit getBaseUnit() {
 436                 return WEEKS;
 437             }
 438             @Override
 439             public TemporalUnit getRangeUnit() {
 440                 return WEEK_BASED_YEARS;
 441             }
 442             @Override
 443             public ValueRange range() {
 444                 return ValueRange.of(1, 52, 53);
 445             }
 446             @Override
 447             public boolean isSupportedBy(TemporalAccessor temporal) {
 448                 return temporal.isSupported(EPOCH_DAY) && isIso(temporal);
 449             }
 450             @Override
 451             public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
 452                 if (isSupportedBy(temporal) == false) {
 453                     throw new UnsupportedTemporalTypeException("Unsupported field: WeekOfWeekBasedYear");
 454                 }
 455                 return getWeekRange(LocalDate.from(temporal));
 456             }
 457             @Override
 458             public long getFrom(TemporalAccessor temporal) {
 459                 if (isSupportedBy(temporal) == false) {
 460                     throw new UnsupportedTemporalTypeException("Unsupported field: WeekOfWeekBasedYear");
 461                 }
 462                 return getWeek(LocalDate.from(temporal));
 463             }
 464             @SuppressWarnings("unchecked")
 465             @Override
 466             public <R extends Temporal> R adjustInto(R temporal, long newValue) {
 467                 // calls getFrom() to check if supported
 468                 range().checkValidValue(newValue, this);  // lenient range
 469                 return (R) temporal.plus(Math.subtractExact(newValue, getFrom(temporal)), WEEKS);
 470             }
 471             @Override
 472             public ChronoLocalDate resolve(
 473                     Map<TemporalField, Long> fieldValues, TemporalAccessor partialTemporal, ResolverStyle resolverStyle) {
 474                 Long wbyLong = fieldValues.get(WEEK_BASED_YEAR);
 475                 Long dowLong = fieldValues.get(DAY_OF_WEEK);
 476                 if (wbyLong == null || dowLong == null) {
 477                     return null;
 478                 }
 479                 int wby = WEEK_BASED_YEAR.range().checkValidIntValue(wbyLong, WEEK_BASED_YEAR);  // always validate
 480                 long wowby = fieldValues.get(WEEK_OF_WEEK_BASED_YEAR);
 481                 ensureIso(partialTemporal);
 482                 LocalDate date = LocalDate.of(wby, 1, 4);
 483                 if (resolverStyle == ResolverStyle.LENIENT) {
 484                     long dow = dowLong;  // unvalidated
 485                     if (dow > 7) {
 486                         date = date.plusWeeks((dow - 1) / 7);
 487                         dow = ((dow - 1) % 7) + 1;
 488                     } else if (dow < 1) {
 489                         date = date.plusWeeks(Math.subtractExact(dow,  7) / 7);
 490                         dow = ((dow + 6) % 7) + 1;
 491                     }
 492                     date = date.plusWeeks(Math.subtractExact(wowby, 1)).with(DAY_OF_WEEK, dow);
 493                 } else {
 494                     int dow = DAY_OF_WEEK.checkValidIntValue(dowLong);  // validated
 495                     if (wowby < 1 || wowby > 52) {
 496                         if (resolverStyle == ResolverStyle.STRICT) {
 497                             getWeekRange(date).checkValidValue(wowby, this);  // only allow exact range
 498                         } else {  // SMART
 499                             range().checkValidValue(wowby, this);  // allow 1-53 rolling into next year
 500                         }
 501                     }
 502                     date = date.plusWeeks(wowby - 1).with(DAY_OF_WEEK, dow);
 503                 }
 504                 fieldValues.remove(this);
 505                 fieldValues.remove(WEEK_BASED_YEAR);
 506                 fieldValues.remove(DAY_OF_WEEK);
 507                 return date;
 508             }
 509             @Override
 510             public String toString() {
 511                 return "WeekOfWeekBasedYear";
 512             }
 513         },
 514         WEEK_BASED_YEAR {
 515             @Override
 516             public TemporalUnit getBaseUnit() {
 517                 return WEEK_BASED_YEARS;
 518             }
 519             @Override
 520             public TemporalUnit getRangeUnit() {
 521                 return FOREVER;
 522             }
 523             @Override
 524             public ValueRange range() {
 525                 return YEAR.range();
 526             }
 527             @Override
 528             public boolean isSupportedBy(TemporalAccessor temporal) {
 529                 return temporal.isSupported(EPOCH_DAY) && isIso(temporal);
 530             }
 531             @Override
 532             public long getFrom(TemporalAccessor temporal) {
 533                 if (isSupportedBy(temporal) == false) {
 534                     throw new UnsupportedTemporalTypeException("Unsupported field: WeekBasedYear");
 535                 }
 536                 return getWeekBasedYear(LocalDate.from(temporal));
 537             }
 538             public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
 539                 if (isSupportedBy(temporal) == false) {
 540                     throw new UnsupportedTemporalTypeException("Unsupported field: WeekBasedYear");
 541                 }
 542                 return super.rangeRefinedBy(temporal);
 543             }
 544             @SuppressWarnings("unchecked")
 545             @Override
 546             public <R extends Temporal> R adjustInto(R temporal, long newValue) {
 547                 if (isSupportedBy(temporal) == false) {
 548                     throw new UnsupportedTemporalTypeException("Unsupported field: WeekBasedYear");
 549                 }
 550                 int newWby = range().checkValidIntValue(newValue, WEEK_BASED_YEAR);  // strict check
 551                 LocalDate date = LocalDate.from(temporal);
 552                 int dow = date.get(DAY_OF_WEEK);
 553                 int week = getWeek(date);
 554                 if (week == 53 && getWeekRange(newWby) == 52) {
 555                     week = 52;
 556                 }
 557                 LocalDate resolved = LocalDate.of(newWby, 1, 4);  // 4th is guaranteed to be in week one
 558                 int days = (dow - resolved.get(DAY_OF_WEEK)) + ((week - 1) * 7);
 559                 resolved = resolved.plusDays(days);
 560                 return (R) temporal.with(resolved);
 561             }
 562             @Override
 563             public String toString() {
 564                 return "WeekBasedYear";
 565             }
 566         };
 567 
 568         @Override
 569         public boolean isDateBased() {
 570             return true;
 571         }
 572 
 573         @Override
 574         public boolean isTimeBased() {
 575             return false;
 576         }
 577 
 578         @Override
 579         public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
 580             return range();
 581         }
 582 
 583         //-------------------------------------------------------------------------
 584         private static final int[] QUARTER_DAYS = {0, 90, 181, 273, 0, 91, 182, 274};
 585 
 586 
 587         private static void ensureIso(TemporalAccessor temporal) {
 588             if (isIso(temporal) == false) {
 589                 throw new DateTimeException("Resolve requires IsoChronology");
 590             }
 591         }
 592 
 593         private static ValueRange getWeekRange(LocalDate date) {
 594             int wby = getWeekBasedYear(date);
 595             return ValueRange.of(1, getWeekRange(wby));
 596         }
 597 
 598         private static int getWeekRange(int wby) {
 599             LocalDate date = LocalDate.of(wby, 1, 1);
 600             // 53 weeks if standard year starts on Thursday, or Wed in a leap year
 601             if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {
 602                 return 53;
 603             }
 604             return 52;
 605         }
 606 
 607         private static int getWeek(LocalDate date) {
 608             int dow0 = date.getDayOfWeek().ordinal();
 609             int doy0 = date.getDayOfYear() - 1;
 610             int doyThu0 = doy0 + (3 - dow0);  // adjust to mid-week Thursday (which is 3 indexed from zero)
 611             int alignedWeek = doyThu0 / 7;
 612             int firstThuDoy0 = doyThu0 - (alignedWeek * 7);
 613             int firstMonDoy0 = firstThuDoy0 - 3;
 614             if (firstMonDoy0 < -3) {
 615                 firstMonDoy0 += 7;
 616             }
 617             if (doy0 < firstMonDoy0) {
 618                 return (int) getWeekRange(date.withDayOfYear(180).minusYears(1)).getMaximum();
 619             }
 620             int week = ((doy0 - firstMonDoy0) / 7) + 1;
 621             if (week == 53) {
 622                 if ((firstMonDoy0 == -3 || (firstMonDoy0 == -2 && date.isLeapYear())) == false) {
 623                     week = 1;
 624                 }
 625             }
 626             return week;
 627         }
 628 
 629         private static int getWeekBasedYear(LocalDate date) {
 630             int year = date.getYear();
 631             int doy = date.getDayOfYear();
 632             if (doy <= 3) {
 633                 int dow = date.getDayOfWeek().ordinal();
 634                 if (doy - dow < -2) {
 635                     year--;
 636                 }
 637             } else if (doy >= 363) {
 638                 int dow = date.getDayOfWeek().ordinal();
 639                 doy = doy - 363 - (date.isLeapYear() ? 1 : 0);
 640                 if (doy - dow >= 0) {
 641                     year++;
 642                 }
 643             }
 644             return year;
 645         }
 646     }
 647 
 648     //-----------------------------------------------------------------------
 649     /**
 650      * Implementation of the unit.
 651      */
 652     private static enum Unit implements TemporalUnit {
 653 
 654         /**
 655          * Unit that represents the concept of a week-based-year.
 656          */
 657         WEEK_BASED_YEARS("WeekBasedYears", Duration.ofSeconds(31556952L)),
 658         /**
 659          * Unit that represents the concept of a quarter-year.
 660          */
 661         QUARTER_YEARS("QuarterYears", Duration.ofSeconds(31556952L / 4));
 662 
 663         private final String name;
 664         private final Duration duration;
 665 
 666         private Unit(String name, Duration estimatedDuration) {
 667             this.name = name;
 668             this.duration = estimatedDuration;
 669         }
 670 
 671         @Override
 672         public Duration getDuration() {
 673             return duration;
 674         }
 675 
 676         @Override
 677         public boolean isDurationEstimated() {
 678             return true;
 679         }
 680 
 681         @Override
 682         public boolean isDateBased() {
 683             return true;
 684         }
 685 
 686         @Override
 687         public boolean isTimeBased() {
 688             return false;
 689         }
 690 
 691         @Override
 692         public boolean isSupportedBy(Temporal temporal) {
 693             return temporal.isSupported(EPOCH_DAY) && isIso(temporal);
 694         }
 695 
 696         @SuppressWarnings("unchecked")
 697         @Override
 698         public <R extends Temporal> R addTo(R temporal, long amount) {
 699             switch (this) {
 700                 case WEEK_BASED_YEARS:
 701                     return (R) temporal.with(WEEK_BASED_YEAR,
 702                             Math.addExact(temporal.get(WEEK_BASED_YEAR), amount));
 703                 case QUARTER_YEARS:
 704                     // no overflow (256 is multiple of 4)
 705                     return (R) temporal.plus(amount / 256, YEARS)
 706                             .plus((amount % 256) * 3, MONTHS);
 707                 default:
 708                     throw new IllegalStateException("Unreachable");
 709             }
 710         }
 711 
 712         @Override
 713         public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) {
 714             if (temporal1Inclusive.getClass() != temporal2Exclusive.getClass()) {
 715                 return temporal1Inclusive.until(temporal2Exclusive, this);
 716             }
 717             switch(this) {
 718                 case WEEK_BASED_YEARS:
 719                     return Math.subtractExact(temporal2Exclusive.getLong(WEEK_BASED_YEAR),
 720                             temporal1Inclusive.getLong(WEEK_BASED_YEAR));
 721                 case QUARTER_YEARS:
 722                     return temporal1Inclusive.until(temporal2Exclusive, MONTHS) / 3;
 723                 default:
 724                     throw new IllegalStateException("Unreachable");
 725             }
 726         }
 727 
 728         @Override
 729         public String toString() {
 730             return name;
 731         }
 732     }
 733 
 734     static boolean isIso(TemporalAccessor temporal) {
 735         return Chronology.from(temporal).equals(IsoChronology.INSTANCE);
 736     }
 737 }