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