src/share/classes/java/time/temporal/WeekFields.java

Print this page




  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.


 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      */


 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


 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 }


  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.


 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      */


 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


 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 }