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  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2011-2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time.temporal;
  63 
  64 import java.io.InvalidObjectException;
  65 import java.io.Serializable;
  66 import java.time.DayOfWeek;
  67 import java.time.format.DateTimeBuilder;
  68 import java.util.GregorianCalendar;
  69 import java.util.Locale;
  70 import java.util.Objects;
  71 import java.util.concurrent.ConcurrentHashMap;
  72 import java.util.concurrent.ConcurrentMap;
  73 
  74 /**
  75  * Localized definitions of the day-of-week, week-of-month and week-of-year fields.
  76  * <p>
  77  * A standard week is seven days long, but cultures have different definitions for some
  78  * other aspects of a week. This class represents the definition of the week, for the
  79  * purpose of providing {@link TemporalField} instances.
  80  * <p>
  81  * WeekFields provides three fields,
  82  * {@link #dayOfWeek()}, {@link #weekOfMonth()}, and {@link #weekOfYear()}
  83  * that provide access to the values from any {@linkplain Temporal temporal object}.
  84  * <p>
  85  * The computations for day-of-week, week-of-month, and week-of-year are based
  86  * on the  {@linkplain ChronoField#YEAR proleptic-year},
  87  * {@linkplain ChronoField#MONTH_OF_YEAR month-of-year},
  88  * {@linkplain ChronoField#DAY_OF_MONTH day-of-month}, and
  89  * {@linkplain ChronoField#DAY_OF_WEEK ISO day-of-week} which are based on the
  90  * {@linkplain ChronoField#EPOCH_DAY epoch-day} and the chronology.
  91  * The values may not be aligned with the {@linkplain ChronoField#YEAR_OF_ERA year-of-Era}
  92  * depending on the Chronology.
  93  * <p>A week is defined by:
  94  * <ul>
  95  * <li>The first day-of-week.
  96  * For example, the ISO-8601 standard considers Monday to be the first day-of-week.
  97  * <li>The minimal number of days in the first week.
  98  * For example, the ISO-08601 standard counts the first week as needing at least 4 days.
  99  * </ul><p>
 100  * Together these two values allow a year or month to be divided into weeks.
 101  * <p>
 102  * <h3>Week of Month</h3>
 103  * One field is used: week-of-month.
 104  * The calculation ensures that weeks never overlap a month boundary.
 105  * The month is divided into periods where each period starts on the defined first day-of-week.
 106  * The earliest period is referred to as week 0 if it has less than the minimal number of days
 107  * and week 1 if it has at least the minimal number of days.
 108  * <p>
 109  * <table cellpadding="0" cellspacing="3" border="0" style="text-align: left; width: 50%;">
 110  * <caption>Examples of WeekFields</caption>
 111  * <tr><th>Date</th><td>Day-of-week</td>
 112  *  <td>First day: Monday<br>Minimal days: 4</td><td>First day: Monday<br>Minimal days: 5</td></tr>
 113  * <tr><th>2008-12-31</th><td>Wednesday</td>
 114  *  <td>Week 5 of December 2008</td><td>Week 5 of December 2008</td></tr>
 115  * <tr><th>2009-01-01</th><td>Thursday</td>
 116  *  <td>Week 1 of January 2009</td><td>Week 0 of January 2009</td></tr>
 117  * <tr><th>2009-01-04</th><td>Sunday</td>
 118  *  <td>Week 1 of January 2009</td><td>Week 0 of January 2009</td></tr>
 119  * <tr><th>2009-01-05</th><td>Monday</td>
 120  *  <td>Week 2 of January 2009</td><td>Week 1 of January 2009</td></tr>
 121  * </table>
 122  * <p>
 123  * <h3>Week of Year</h3>
 124  * One field is used: week-of-year.
 125  * The calculation ensures that weeks never overlap a year boundary.
 126  * The year is divided into periods where each period starts on the defined first day-of-week.
 127  * The earliest period is referred to as week 0 if it has less than the minimal number of days
 128  * and week 1 if it has at least the minimal number of days.
 129  * <p>
 130  * This class is immutable and thread-safe.
 131  *
 132  * @since 1.8
 133  */
 134 public final class WeekFields implements Serializable {
 135     // implementation notes
 136     // querying week-of-month or week-of-year should return the week value bound within the month/year
 137     // however, setting the week value should be lenient (use plus/minus weeks)
 138     // allow week-of-month outer range [0 to 5]
 139     // allow week-of-year outer range [0 to 53]
 140     // this is because callers shouldn't be expected to know the details of validity
 141 
 142     /**
 143      * The cache of rules by firstDayOfWeek plus minimalDays.
 144      * Initialized first to be available for definition of ISO, etc.
 145      */
 146     private static final ConcurrentMap<String, WeekFields> CACHE = new ConcurrentHashMap<>(4, 0.75f, 2);
 147 
 148     /**
 149      * The ISO-8601 definition, where a week starts on Monday and the first week
 150      * has a minimum of 4 days.
 151      * <p>
 152      * The ISO-8601 standard defines a calendar system based on weeks.
 153      * It uses the week-based-year and week-of-week-based-year concepts to split
 154      * up the passage of days instead of the standard year/month/day.
 155      * <p>
 156      * Note that the first week may start in the previous calendar year.
 157      * Note also that the first few days of a calendar year may be in the
 158      * week-based-year corresponding to the previous calendar year.
 159      */
 160     public static final WeekFields ISO = new WeekFields(DayOfWeek.MONDAY, 4);
 161 
 162     /**
 163      * The common definition of a week that starts on Sunday.
 164      * <p>
 165      * Defined as starting on Sunday and with a minimum of 1 day in the month.
 166      * This week definition is in use in the US and other European countries.
 167      *
 168      */
 169     public static final WeekFields SUNDAY_START = WeekFields.of(DayOfWeek.SUNDAY, 1);
 170 
 171     /**
 172      * Serialization version.
 173      */
 174     private static final long serialVersionUID = -1177360819670808121L;
 175 
 176     /**
 177      * The first day-of-week.
 178      */
 179     private final DayOfWeek firstDayOfWeek;
 180     /**
 181      * The minimal number of days in the first week.
 182      */
 183     private final int minimalDays;
 184 
 185     /**
 186      * The field used to access the computed DayOfWeek.
 187      */
 188     private transient final TemporalField dayOfWeek = ComputedDayOfField.ofDayOfWeekField(this);
 189 
 190     /**
 191      * The field used to access the computed WeekOfMonth.
 192      */
 193     private transient final TemporalField weekOfMonth = ComputedDayOfField.ofWeekOfMonthField(this);
 194 
 195     /**
 196      * The field used to access the computed WeekOfYear.
 197      */
 198     private transient final TemporalField weekOfYear = ComputedDayOfField.ofWeekOfYearField(this);
 199 
 200     /**
 201      * Obtains an instance of {@code WeekFields} appropriate for a locale.
 202      * <p>
 203      * This will look up appropriate values from the provider of localization data.
 204      *
 205      * @param locale  the locale to use, not null
 206      * @return the week-definition, not null
 207      */
 208     public static WeekFields of(Locale locale) {
 209         Objects.requireNonNull(locale, "locale");
 210         locale = new Locale(locale.getLanguage(), locale.getCountry());  // elminate variants
 211 
 212         // obtain these from GregorianCalendar for now
 213         // TODO: consider getting them directly from the spi
 214         GregorianCalendar gcal = new GregorianCalendar(locale);
 215         int calDow = gcal.getFirstDayOfWeek();
 216         DayOfWeek dow = DayOfWeek.SUNDAY.plus(calDow - 1);
 217         int minDays = gcal.getMinimalDaysInFirstWeek();
 218         return WeekFields.of(dow, minDays);
 219     }
 220 
 221     /**
 222      * Obtains an instance of {@code WeekFields} from the first day-of-week and minimal days.
 223      * <p>
 224      * The first day-of-week defines the ISO {@code DayOfWeek} that is day 1 of the week.
 225      * The minimal number of days in the first week defines how many days must be present
 226      * in a month or year, starting from the first day-of-week, before the week is counted
 227      * as the first week. A value of 1 will count the first day of the month or year as part
 228      * of the first week, whereas a value of 7 will require the whole seven days to be in
 229      * the new month or year.
 230      * <p>
 231      * WeekFields instances are singletons; for each unique combination
 232      * of {@code firstDayOfWeek} and {@code minimalDaysInFirstWeek} the
 233      * the same instance will be returned.
 234      *
 235      * @param firstDayOfWeek  the first day of the week, not null
 236      * @param minimalDaysInFirstWeek  the minimal number of days in the first week, from 1 to 7
 237      * @return the week-definition, not null
 238      * @throws IllegalArgumentException if the minimal days value is less than one
 239      *      or greater than 7
 240      */
 241     public static WeekFields of(DayOfWeek firstDayOfWeek, int minimalDaysInFirstWeek) {
 242         String key = firstDayOfWeek.toString() + minimalDaysInFirstWeek;
 243         WeekFields rules = CACHE.get(key);
 244         if (rules == null) {
 245             rules = new WeekFields(firstDayOfWeek, minimalDaysInFirstWeek);
 246             CACHE.putIfAbsent(key, rules);
 247             rules = CACHE.get(key);
 248         }
 249         return rules;
 250     }
 251 
 252     //-----------------------------------------------------------------------
 253     /**
 254      * Creates an instance of the definition.
 255      *
 256      * @param firstDayOfWeek  the first day of the week, not null
 257      * @param minimalDaysInFirstWeek  the minimal number of days in the first week, from 1 to 7
 258      * @throws IllegalArgumentException if the minimal days value is invalid
 259      */
 260     private WeekFields(DayOfWeek firstDayOfWeek, int minimalDaysInFirstWeek) {
 261         Objects.requireNonNull(firstDayOfWeek, "firstDayOfWeek");
 262         if (minimalDaysInFirstWeek < 1 || minimalDaysInFirstWeek > 7) {
 263             throw new IllegalArgumentException("Minimal number of days is invalid");
 264         }
 265         this.firstDayOfWeek = firstDayOfWeek;
 266         this.minimalDays = minimalDaysInFirstWeek;
 267     }
 268 
 269     //-----------------------------------------------------------------------
 270     /**
 271      * Return the singleton WeekFields associated with the
 272      * {@code firstDayOfWeek} and {@code minimalDays}.
 273      * @return the singleton WeekFields for the firstDayOfWeek and minimalDays.
 274      * @throws InvalidObjectException if the serialized object has invalid
 275      *     values for firstDayOfWeek or minimalDays.
 276      */
 277     private Object readResolve() throws InvalidObjectException {
 278         try {
 279             return WeekFields.of(firstDayOfWeek, minimalDays);
 280         } catch (IllegalArgumentException iae) {
 281             throw new InvalidObjectException("Invalid serialized WeekFields: "
 282                     + iae.getMessage());
 283         }
 284     }
 285 
 286     //-----------------------------------------------------------------------
 287     /**
 288      * Gets the first day-of-week.
 289      * <p>
 290      * The first day-of-week varies by culture.
 291      * For example, the US uses Sunday, while France and the ISO-8601 standard use Monday.
 292      * This method returns the first day using the standard {@code DayOfWeek} enum.
 293      *
 294      * @return the first day-of-week, not null
 295      */
 296     public DayOfWeek getFirstDayOfWeek() {
 297         return firstDayOfWeek;
 298     }
 299 
 300     /**
 301      * Gets the minimal number of days in the first week.
 302      * <p>
 303      * The number of days considered to define the first week of a month or year
 304      * varies by culture.
 305      * For example, the ISO-8601 requires 4 days (more than half a week) to
 306      * be present before counting the first week.
 307      *
 308      * @return the minimal number of days in the first week of a month or year, from 1 to 7
 309      */
 310     public int getMinimalDaysInFirstWeek() {
 311         return minimalDays;
 312     }
 313 
 314     //-----------------------------------------------------------------------
 315     /**
 316      * Returns a field to access the day of week,
 317      * computed based on this WeekFields.
 318      * <p>
 319      * The days of week are numbered from 1 to 7.
 320      * Day number 1 is the {@link #getFirstDayOfWeek() first day-of-week}.
 321      *
 322      * @return the field for day-of-week using this week definition, not null
 323      */
 324     public TemporalField dayOfWeek() {
 325         return dayOfWeek;
 326     }
 327 
 328     /**
 329      * Returns a field to access the week of month,
 330      * computed based on this WeekFields.
 331      * <p>
 332      * This represents concept of the count of weeks within the month where weeks
 333      * start on a fixed day-of-week, such as Monday.
 334      * This field is typically used with {@link WeekFields#dayOfWeek()}.
 335      * <p>
 336      * Week one (1) is the week starting on the {@link WeekFields#getFirstDayOfWeek}
 337      * where there are at least {@link WeekFields#getMinimalDaysInFirstWeek()} days in the month.
 338      * Thus, week one may start up to {@code minDays} days before the start of the month.
 339      * If the first week starts after the start of the month then the period before is week zero (0).
 340      * <p>
 341      * For example:<br>
 342      * - if the 1st day of the month is a Monday, week one starts on the 1st and there is no week zero<br>
 343      * - if the 2nd day of the month is a Monday, week one starts on the 2nd and the 1st is in week zero<br>
 344      * - if the 4th day of the month is a Monday, week one starts on the 4th and the 1st to 3rd is in week zero<br>
 345      * - if the 5th day of the month is a Monday, week two starts on the 5th and the 1st to 4th is in week one<br>
 346      * <p>
 347      * This field can be used with any calendar system.
 348      * @return a TemporalField to access the WeekOfMonth, not null
 349      */
 350     public TemporalField weekOfMonth() {
 351         return weekOfMonth;
 352     }
 353 
 354     /**
 355      * Returns a field to access the week of year,
 356      * computed based on this WeekFields.
 357      * <p>
 358      * This represents concept of the count of weeks within the year where weeks
 359      * start on a fixed day-of-week, such as Monday.
 360      * This field is typically used with {@link WeekFields#dayOfWeek()}.
 361      * <p>
 362      * Week one(1) is the week starting on the {@link WeekFields#getFirstDayOfWeek}
 363      * where there are at least {@link WeekFields#getMinimalDaysInFirstWeek()} days in the month.
 364      * Thus, week one may start up to {@code minDays} days before the start of the year.
 365      * If the first week starts after the start of the year then the period before is week zero (0).
 366      * <p>
 367      * For example:<br>
 368      * - if the 1st day of the year is a Monday, week one starts on the 1st and there is no week zero<br>
 369      * - if the 2nd day of the year is a Monday, week one starts on the 2nd and the 1st is in week zero<br>
 370      * - if the 4th day of the year is a Monday, week one starts on the 4th and the 1st to 3rd is in week zero<br>
 371      * - if the 5th day of the year is a Monday, week two starts on the 5th and the 1st to 4th is in week one<br>
 372      * <p>
 373      * This field can be used with any calendar system.
 374      * @return a TemporalField to access the WeekOfYear, not null
 375      */
 376     public TemporalField weekOfYear() {
 377         return weekOfYear;
 378     }
 379 
 380     /**
 381      * Checks if these rules are equal to the specified rules.
 382      * <p>
 383      * The comparison is based on the entire state of the rules, which is
 384      * the first day-of-week and minimal days.
 385      *
 386      * @param object  the other rules to compare to, null returns false
 387      * @return true if this is equal to the specified rules
 388      */
 389     @Override
 390     public boolean equals(Object object) {
 391         if (this == object) {
 392             return true;
 393         }
 394         if (object instanceof WeekFields) {
 395             return hashCode() == object.hashCode();
 396         }
 397         return false;
 398     }
 399 
 400     /**
 401      * A hash code for these rules.
 402      *
 403      * @return a suitable hash code
 404      */
 405     @Override
 406     public int hashCode() {
 407         return firstDayOfWeek.ordinal() * 7 + minimalDays;
 408     }
 409 
 410     //-----------------------------------------------------------------------
 411     /**
 412      * A string representation of this definition.
 413      *
 414      * @return the string representation, not null
 415      */
 416     @Override
 417     public String toString() {
 418         return "WeekFields[" + firstDayOfWeek + ',' + minimalDays + ']';
 419     }
 420 
 421     //-----------------------------------------------------------------------
 422     /**
 423      * Field type that computes DayOfWeek, WeekOfMonth, and WeekOfYear
 424      * based on a WeekFields.
 425      * A separate Field instance is required for each different WeekFields;
 426      * combination of start of week and minimum number of days.
 427      * Constructors are provided to create fields for DayOfWeek, WeekOfMonth,
 428      * and WeekOfYear.
 429      */
 430     static class ComputedDayOfField implements TemporalField {
 431 
 432         /**
 433          * Returns a field to access the day of week,
 434          * computed based on a WeekFields.
 435          * <p>
 436          * The WeekDefintion of the first day of the week is used with
 437          * the ISO DAY_OF_WEEK field to compute week boundaries.
 438          */
 439         static ComputedDayOfField ofDayOfWeekField(WeekFields weekDef) {
 440             return new ComputedDayOfField("DayOfWeek", weekDef,
 441                     ChronoUnit.DAYS, ChronoUnit.WEEKS, DAY_OF_WEEK_RANGE);
 442         }
 443 
 444         /**
 445          * Returns a field to access the week of month,
 446          * computed based on a WeekFields.
 447          * @see WeekFields#weekOfMonth()
 448          */
 449         static ComputedDayOfField ofWeekOfMonthField(WeekFields weekDef) {
 450             return new ComputedDayOfField("WeekOfMonth", weekDef,
 451                     ChronoUnit.WEEKS, ChronoUnit.MONTHS, WEEK_OF_MONTH_RANGE);
 452         }
 453 
 454         /**
 455          * Returns a field to access the week of year,
 456          * computed based on a WeekFields.
 457          * @see WeekFields#weekOfYear()
 458          */
 459         static ComputedDayOfField ofWeekOfYearField(WeekFields weekDef) {
 460             return new ComputedDayOfField("WeekOfYear", weekDef,
 461                     ChronoUnit.WEEKS, ChronoUnit.YEARS, WEEK_OF_YEAR_RANGE);
 462         }
 463         private final String name;
 464         private final WeekFields weekDef;
 465         private final TemporalUnit baseUnit;
 466         private final TemporalUnit rangeUnit;
 467         private final ValueRange range;
 468 
 469         private ComputedDayOfField(String name, WeekFields weekDef, TemporalUnit baseUnit, TemporalUnit rangeUnit, ValueRange range) {
 470             this.name = name;
 471             this.weekDef = weekDef;
 472             this.baseUnit = baseUnit;
 473             this.rangeUnit = rangeUnit;
 474             this.range = range;
 475         }
 476 
 477         private static final ValueRange DAY_OF_WEEK_RANGE = ValueRange.of(1, 7);
 478         private static final ValueRange WEEK_OF_MONTH_RANGE = ValueRange.of(0, 1, 4, 5);
 479         private static final ValueRange WEEK_OF_YEAR_RANGE = ValueRange.of(0, 1, 52, 53);
 480 
 481         @Override
 482         public long doGet(TemporalAccessor temporal) {
 483             // Offset the ISO DOW by the start of this week
 484             int sow = weekDef.getFirstDayOfWeek().getValue();
 485             int isoDow = temporal.get(ChronoField.DAY_OF_WEEK);
 486             int dow = Math.floorMod(isoDow - sow, 7) + 1;
 487 
 488             if (rangeUnit == ChronoUnit.WEEKS) {
 489                 return dow;
 490             } else if (rangeUnit == ChronoUnit.MONTHS) {
 491                 int dom = temporal.get(ChronoField.DAY_OF_MONTH);
 492                 int offset = startOfWeekOffset(dom, dow);
 493                 return computeWeek(offset, dom);
 494             } else if (rangeUnit == ChronoUnit.YEARS) {
 495                 int doy = temporal.get(ChronoField.DAY_OF_YEAR);
 496                 int offset = startOfWeekOffset(doy, dow);
 497                 return computeWeek(offset, doy);
 498             } else {
 499                 throw new IllegalStateException("unreachable");
 500             }
 501         }
 502 
 503         /**
 504          * Returns an offset to align week start with a day of month or day of year.
 505          *
 506          * @param day the day; 1 through infinity
 507          * @param dow the day of the week of that day; 1 through 7
 508          * @return an offset in days to align a day with the start of the first 'full' week
 509          */
 510         private int startOfWeekOffset(int day, int dow) {
 511             // offset of first day corresponding to the day of week in first 7 days (zero origin)
 512             int weekStart = Math.floorMod(day - dow, 7);
 513             int offset = -weekStart;
 514             if (weekStart + 1 > weekDef.getMinimalDaysInFirstWeek()) {
 515                 // The previous week has the minimum days in the current month to be a 'week'
 516                 offset = 7 - weekStart;
 517             }
 518             return offset;
 519         }
 520 
 521         /**
 522          * Returns the week number computed from the reference day and reference dayOfWeek.
 523          *
 524          * @param offset the offset to align a date with the start of week
 525          *     from {@link #startOfWeekOffset}.
 526          * @param day  the day for which to compute the week number
 527          * @return the week number where zero is used for a partial week and 1 for the first full week
 528          */
 529         private int computeWeek(int offset, int day) {
 530             return ((7 + offset + (day - 1)) / 7);
 531         }
 532 
 533         @Override
 534         public <R extends Temporal> R doWith(R temporal, long newValue) {
 535             // Check the new value and get the old value of the field
 536             int newVal = range.checkValidIntValue(newValue, this);
 537             int currentVal = temporal.get(this);
 538             if (newVal == currentVal) {
 539                 return temporal;
 540             }
 541             // Compute the difference and add that using the base using of the field
 542             int delta = newVal - currentVal;
 543             return (R) temporal.plus(delta, baseUnit);
 544         }
 545 
 546         @Override
 547         public boolean resolve(DateTimeBuilder builder, long value) {
 548             int newValue = range.checkValidIntValue(value, this);
 549             // DOW and YEAR are necessary for all fields; Chrono defaults to ISO if not present
 550             int sow = weekDef.getFirstDayOfWeek().getValue();
 551             int dow = builder.get(weekDef.dayOfWeek());
 552             int year = builder.get(ChronoField.YEAR);
 553             Chrono chrono = Chrono.from(builder);
 554 
 555             // The WOM and WOY fields are the critical values
 556             if (rangeUnit == ChronoUnit.MONTHS) {
 557                 // Process WOM value by combining with DOW and MONTH, YEAR
 558                 int month = builder.get(ChronoField.MONTH_OF_YEAR);
 559                 ChronoLocalDate cd = chrono.date(year, month, 1);
 560                 int offset = startOfWeekOffset(1, cd.get(weekDef.dayOfWeek()));
 561                 offset += dow - 1;    // offset to desired day of week
 562                 offset += 7 * (newValue - 1);    // offset by week number
 563                 ChronoLocalDate result = cd.plus(offset, ChronoUnit.DAYS);
 564                 builder.addFieldValue(ChronoField.DAY_OF_MONTH, result.get(ChronoField.DAY_OF_MONTH));
 565                 builder.removeFieldValue(this);
 566                 builder.removeFieldValue(weekDef.dayOfWeek());
 567                 return true;
 568             } else if (rangeUnit == ChronoUnit.YEARS) {
 569                 // Process WOY
 570                 ChronoLocalDate cd = chrono.date(year, 1, 1);
 571                 int offset = startOfWeekOffset(1, cd.get(weekDef.dayOfWeek()));
 572                 offset += dow - 1;    // offset to desired day of week
 573                 offset += 7 * (newValue - 1);    // offset by week number
 574                 ChronoLocalDate result = cd.plus(offset, ChronoUnit.DAYS);
 575                 builder.addFieldValue(ChronoField.DAY_OF_MONTH, result.get(ChronoField.DAY_OF_MONTH));
 576                 builder.addFieldValue(ChronoField.MONTH_OF_YEAR, result.get(ChronoField.MONTH_OF_YEAR));
 577                 builder.removeFieldValue(this);
 578                 builder.removeFieldValue(weekDef.dayOfWeek());
 579                 return true;
 580             } else {
 581                 // ignore DOW of WEEK field; the value will be processed by WOM or WOY
 582                 int isoDow = Math.floorMod((sow - 1) + (dow - 1), 7) + 1;
 583                 builder.addFieldValue(ChronoField.DAY_OF_WEEK, isoDow);
 584                 // Not removed, the week-of-xxx fields need this value
 585                 return true;
 586             }
 587         }
 588 
 589         //-----------------------------------------------------------------------
 590         @Override
 591         public String getName() {
 592             return name;
 593         }
 594 
 595         @Override
 596         public TemporalUnit getBaseUnit() {
 597             return baseUnit;
 598         }
 599 
 600         @Override
 601         public TemporalUnit getRangeUnit() {
 602             return rangeUnit;
 603         }
 604 
 605         @Override
 606         public ValueRange range() {
 607             return range;
 608         }
 609 
 610         //-------------------------------------------------------------------------
 611         @Override
 612         public int compare(TemporalAccessor temporal1, TemporalAccessor temporal2) {
 613             return Long.compare(temporal1.getLong(this), temporal2.getLong(this));
 614         }
 615 
 616         //-----------------------------------------------------------------------
 617         @Override
 618         public boolean doIsSupported(TemporalAccessor temporal) {
 619             if (temporal.isSupported(ChronoField.DAY_OF_WEEK)) {
 620                 if (rangeUnit == ChronoUnit.WEEKS) {
 621                     return true;
 622                 } else if (rangeUnit == ChronoUnit.MONTHS) {
 623                     return temporal.isSupported(ChronoField.DAY_OF_MONTH);
 624                 } else if (rangeUnit == ChronoUnit.YEARS) {
 625                     return temporal.isSupported(ChronoField.DAY_OF_YEAR);
 626                 }
 627             }
 628             return false;
 629         }
 630 
 631         @Override
 632         public ValueRange doRange(TemporalAccessor temporal) {
 633             if (rangeUnit == ChronoUnit.WEEKS) {
 634                 return range;
 635             }
 636 
 637             TemporalField field = null;
 638             if (rangeUnit == ChronoUnit.MONTHS) {
 639                 field = ChronoField.DAY_OF_MONTH;
 640             } else if (rangeUnit == ChronoUnit.YEARS) {
 641                 field = ChronoField.DAY_OF_YEAR;
 642             } else {
 643                 throw new IllegalStateException("unreachable");
 644             }
 645 
 646             // Offset the ISO DOW by the start of this week
 647             int sow = weekDef.getFirstDayOfWeek().getValue();
 648             int isoDow = temporal.get(ChronoField.DAY_OF_WEEK);
 649             int dow = Math.floorMod(isoDow - sow, 7) + 1;
 650 
 651             int offset = startOfWeekOffset(temporal.get(field), dow);
 652             ValueRange fieldRange = temporal.range(field);
 653             return ValueRange.of(computeWeek(offset, (int) fieldRange.getMinimum()),
 654                     computeWeek(offset, (int) fieldRange.getMaximum()));
 655         }
 656 
 657         //-----------------------------------------------------------------------
 658         @Override
 659         public String toString() {
 660             return getName() + "[" + weekDef.toString() + "]";
 661         }
 662     }
 663 }