Path: blob/master/src/java.base/share/classes/java/time/temporal/WeekFields.java
41159 views
/*1* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2011-2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time.temporal;6263import static java.time.temporal.ChronoField.DAY_OF_MONTH;64import static java.time.temporal.ChronoField.DAY_OF_WEEK;65import static java.time.temporal.ChronoField.DAY_OF_YEAR;66import static java.time.temporal.ChronoField.MONTH_OF_YEAR;67import static java.time.temporal.ChronoField.YEAR;68import static java.time.temporal.ChronoUnit.DAYS;69import static java.time.temporal.ChronoUnit.FOREVER;70import static java.time.temporal.ChronoUnit.MONTHS;71import static java.time.temporal.ChronoUnit.WEEKS;72import static java.time.temporal.ChronoUnit.YEARS;7374import java.io.IOException;75import java.io.InvalidObjectException;76import java.io.ObjectInputStream;77import java.io.Serializable;78import java.time.DateTimeException;79import java.time.DayOfWeek;80import java.time.chrono.ChronoLocalDate;81import java.time.chrono.Chronology;82import java.time.format.ResolverStyle;83import java.util.Locale;84import java.util.Map;85import java.util.Objects;86import java.util.ResourceBundle;87import java.util.concurrent.ConcurrentHashMap;88import java.util.concurrent.ConcurrentMap;89import sun.util.locale.provider.CalendarDataUtility;90import sun.util.locale.provider.LocaleProviderAdapter;91import sun.util.locale.provider.LocaleResources;9293/**94* Localized definitions of the day-of-week, week-of-month and week-of-year fields.95* <p>96* A standard week is seven days long, but cultures have different definitions for some97* other aspects of a week. This class represents the definition of the week, for the98* purpose of providing {@link TemporalField} instances.99* <p>100* WeekFields provides five fields,101* {@link #dayOfWeek()}, {@link #weekOfMonth()}, {@link #weekOfYear()},102* {@link #weekOfWeekBasedYear()}, and {@link #weekBasedYear()}103* that provide access to the values from any {@linkplain Temporal temporal object}.104* <p>105* The computations for day-of-week, week-of-month, and week-of-year are based106* on the {@linkplain ChronoField#YEAR proleptic-year},107* {@linkplain ChronoField#MONTH_OF_YEAR month-of-year},108* {@linkplain ChronoField#DAY_OF_MONTH day-of-month}, and109* {@linkplain ChronoField#DAY_OF_WEEK ISO day-of-week} which are based on the110* {@linkplain ChronoField#EPOCH_DAY epoch-day} and the chronology.111* The values may not be aligned with the {@linkplain ChronoField#YEAR_OF_ERA year-of-Era}112* depending on the Chronology.113* <p>A week is defined by:114* <ul>115* <li>The first day-of-week.116* For example, the ISO-8601 standard considers Monday to be the first day-of-week.117* <li>The minimal number of days in the first week.118* For example, the ISO-8601 standard counts the first week as needing at least 4 days.119* </ul>120* Together these two values allow a year or month to be divided into weeks.121*122* <h2>Week of Month</h2>123* One field is used: week-of-month.124* The calculation ensures that weeks never overlap a month boundary.125* The month is divided into periods where each period starts on the defined first day-of-week.126* The earliest period is referred to as week 0 if it has less than the minimal number of days127* and week 1 if it has at least the minimal number of days.128*129* <table class=striped style="text-align: left">130* <caption>Examples of WeekFields</caption>131* <thead>132* <tr><th scope="col">Date</th><th scope="col">Day-of-week</th>133* <th scope="col">First day: Monday<br>Minimal days: 4</th><th scope="col">First day: Monday<br>Minimal days: 5</th></tr>134* </thead>135* <tbody>136* <tr><th scope="row">2008-12-31</th><td>Wednesday</td>137* <td>Week 5 of December 2008</td><td>Week 5 of December 2008</td></tr>138* <tr><th scope="row">2009-01-01</th><td>Thursday</td>139* <td>Week 1 of January 2009</td><td>Week 0 of January 2009</td></tr>140* <tr><th scope="row">2009-01-04</th><td>Sunday</td>141* <td>Week 1 of January 2009</td><td>Week 0 of January 2009</td></tr>142* <tr><th scope="row">2009-01-05</th><td>Monday</td>143* <td>Week 2 of January 2009</td><td>Week 1 of January 2009</td></tr>144* </tbody>145* </table>146*147* <h2>Week of Year</h2>148* One field is used: week-of-year.149* The calculation ensures that weeks never overlap a year boundary.150* The year is divided into periods where each period starts on the defined first day-of-week.151* The earliest period is referred to as week 0 if it has less than the minimal number of days152* and week 1 if it has at least the minimal number of days.153*154* <h2>Week Based Year</h2>155* Two fields are used for week-based-year, one for the156* {@link #weekOfWeekBasedYear() week-of-week-based-year} and one for157* {@link #weekBasedYear() week-based-year}. In a week-based-year, each week158* belongs to only a single year. Week 1 of a year is the first week that159* starts on the first day-of-week and has at least the minimum number of days.160* The first and last weeks of a year may contain days from the161* previous calendar year or next calendar year respectively.162*163* <table class=striped style="text-align: left;">164* <caption>Examples of WeekFields for week-based-year</caption>165* <thead>166* <tr><th scope="col">Date</th><th scope="col">Day-of-week</th>167* <th scope="col">First day: Monday<br>Minimal days: 4</th><th scope="col">First day: Monday<br>Minimal days: 5</th></tr>168* </thead>169* <tbody>170* <tr><th scope="row">2008-12-31</th><td>Wednesday</td>171* <td>Week 1 of 2009</td><td>Week 53 of 2008</td></tr>172* <tr><th scope="row">2009-01-01</th><td>Thursday</td>173* <td>Week 1 of 2009</td><td>Week 53 of 2008</td></tr>174* <tr><th scope="row">2009-01-04</th><td>Sunday</td>175* <td>Week 1 of 2009</td><td>Week 53 of 2008</td></tr>176* <tr><th scope="row">2009-01-05</th><td>Monday</td>177* <td>Week 2 of 2009</td><td>Week 1 of 2009</td></tr>178* </tbody>179* </table>180*181* @implSpec182* This class is immutable and thread-safe.183*184* @since 1.8185*/186public final class WeekFields implements Serializable {187// implementation notes188// querying week-of-month or week-of-year should return the week value bound within the month/year189// however, setting the week value should be lenient (use plus/minus weeks)190// allow week-of-month outer range [0 to 6]191// allow week-of-year outer range [0 to 54]192// this is because callers shouldn't be expected to know the details of validity193194/**195* The cache of rules by firstDayOfWeek plus minimalDays.196* Initialized first to be available for definition of ISO, etc.197*/198private static final ConcurrentMap<String, WeekFields> CACHE = new ConcurrentHashMap<>(4, 0.75f, 2);199200/**201* The ISO-8601 definition, where a week starts on Monday and the first week202* has a minimum of 4 days.203* <p>204* The ISO-8601 standard defines a calendar system based on weeks.205* It uses the week-based-year and week-of-week-based-year concepts to split206* up the passage of days instead of the standard year/month/day.207* <p>208* Note that the first week may start in the previous calendar year.209* Note also that the first few days of a calendar year may be in the210* week-based-year corresponding to the previous calendar year.211*/212public static final WeekFields ISO = WeekFields.of(DayOfWeek.MONDAY, 4);213214/**215* The common definition of a week that starts on Sunday and the first week216* has a minimum of 1 day.217* <p>218* Defined as starting on Sunday and with a minimum of 1 day in the month.219* This week definition is in use in the US and other European countries.220*/221public static final WeekFields SUNDAY_START = WeekFields.of(DayOfWeek.SUNDAY, 1);222223/**224* The unit that represents week-based-years for the purpose of addition and subtraction.225* <p>226* This allows a number of week-based-years to be added to, or subtracted from, a date.227* The unit is equal to either 52 or 53 weeks.228* The estimated duration of a week-based-year is the same as that of a standard ISO229* year at {@code 365.2425 Days}.230* <p>231* The rules for addition add the number of week-based-years to the existing value232* for the week-based-year field retaining the week-of-week-based-year233* and day-of-week, unless the week number it too large for the target year.234* In that case, the week is set to the last week of the year235* with the same day-of-week.236* <p>237* This unit is an immutable and thread-safe singleton.238*/239public static final TemporalUnit WEEK_BASED_YEARS = IsoFields.WEEK_BASED_YEARS;240241/**242* Serialization version.243*/244@java.io.Serial245private static final long serialVersionUID = -1177360819670808121L;246247/**248* The first day-of-week.249*/250private final DayOfWeek firstDayOfWeek;251/**252* The minimal number of days in the first week.253*/254private final int minimalDays;255/**256* The field used to access the computed DayOfWeek.257*/258private final transient TemporalField dayOfWeek = ComputedDayOfField.ofDayOfWeekField(this);259/**260* The field used to access the computed WeekOfMonth.261*/262private final transient TemporalField weekOfMonth = ComputedDayOfField.ofWeekOfMonthField(this);263/**264* The field used to access the computed WeekOfYear.265*/266private final transient TemporalField weekOfYear = ComputedDayOfField.ofWeekOfYearField(this);267/**268* The field that represents the week-of-week-based-year.269* <p>270* This field allows the week of the week-based-year value to be queried and set.271* <p>272* This unit is an immutable and thread-safe singleton.273*/274private final transient TemporalField weekOfWeekBasedYear = ComputedDayOfField.ofWeekOfWeekBasedYearField(this);275/**276* The field that represents the week-based-year.277* <p>278* This field allows the week-based-year value to be queried and set.279* <p>280* This unit is an immutable and thread-safe singleton.281*/282private final transient TemporalField weekBasedYear = ComputedDayOfField.ofWeekBasedYearField(this);283284//-----------------------------------------------------------------------285/**286* Obtains an instance of {@code WeekFields} appropriate for a locale.287* <p>288* This will look up appropriate values from the provider of localization data.289* If the locale contains "fw" (First day of week) and/or "rg"290* (Region Override) <a href="../../util/Locale.html#def_locale_extension">291* Unicode extensions</a>, returned instance will reflect the values specified with292* those extensions. If both "fw" and "rg" are specified, the value from293* the "fw" extension supersedes the implicit one from the "rg" extension.294*295* @param locale the locale to use, not null296* @return the week-definition, not null297*/298public static WeekFields of(Locale locale) {299Objects.requireNonNull(locale, "locale");300301int calDow = CalendarDataUtility.retrieveFirstDayOfWeek(locale);302DayOfWeek dow = DayOfWeek.SUNDAY.plus(calDow - 1);303int minDays = CalendarDataUtility.retrieveMinimalDaysInFirstWeek(locale);304return WeekFields.of(dow, minDays);305}306307/**308* Obtains an instance of {@code WeekFields} from the first day-of-week and minimal days.309* <p>310* The first day-of-week defines the ISO {@code DayOfWeek} that is day 1 of the week.311* The minimal number of days in the first week defines how many days must be present312* in a month or year, starting from the first day-of-week, before the week is counted313* as the first week. A value of 1 will count the first day of the month or year as part314* of the first week, whereas a value of 7 will require the whole seven days to be in315* the new month or year.316* <p>317* WeekFields instances are singletons; for each unique combination318* of {@code firstDayOfWeek} and {@code minimalDaysInFirstWeek}319* the same instance will be returned.320*321* @param firstDayOfWeek the first day of the week, not null322* @param minimalDaysInFirstWeek the minimal number of days in the first week, from 1 to 7323* @return the week-definition, not null324* @throws IllegalArgumentException if the minimal days value is less than one325* or greater than 7326*/327public static WeekFields of(DayOfWeek firstDayOfWeek, int minimalDaysInFirstWeek) {328String key = firstDayOfWeek.toString() + minimalDaysInFirstWeek;329WeekFields rules = CACHE.get(key);330if (rules == null) {331rules = new WeekFields(firstDayOfWeek, minimalDaysInFirstWeek);332CACHE.putIfAbsent(key, rules);333rules = CACHE.get(key);334}335return rules;336}337338//-----------------------------------------------------------------------339/**340* Creates an instance of the definition.341*342* @param firstDayOfWeek the first day of the week, not null343* @param minimalDaysInFirstWeek the minimal number of days in the first week, from 1 to 7344* @throws IllegalArgumentException if the minimal days value is invalid345*/346private WeekFields(DayOfWeek firstDayOfWeek, int minimalDaysInFirstWeek) {347Objects.requireNonNull(firstDayOfWeek, "firstDayOfWeek");348if (minimalDaysInFirstWeek < 1 || minimalDaysInFirstWeek > 7) {349throw new IllegalArgumentException("Minimal number of days is invalid");350}351this.firstDayOfWeek = firstDayOfWeek;352this.minimalDays = minimalDaysInFirstWeek;353}354355//-----------------------------------------------------------------------356/**357* Restore the state of a WeekFields from the stream.358* Check that the values are valid.359*360* @param s the stream to read361* @throws IOException if an I/O error occurs362* @throws InvalidObjectException if the serialized object has an invalid363* value for firstDayOfWeek or minimalDays.364* @throws ClassNotFoundException if a class cannot be resolved365*/366@java.io.Serial367private void readObject(ObjectInputStream s)368throws IOException, ClassNotFoundException, InvalidObjectException369{370s.defaultReadObject();371if (firstDayOfWeek == null) {372throw new InvalidObjectException("firstDayOfWeek is null");373}374375if (minimalDays < 1 || minimalDays > 7) {376throw new InvalidObjectException("Minimal number of days is invalid");377}378}379380/**381* Return the singleton WeekFields associated with the382* {@code firstDayOfWeek} and {@code minimalDays}.383* @return the singleton WeekFields for the firstDayOfWeek and minimalDays.384* @throws InvalidObjectException if the serialized object has invalid385* values for firstDayOfWeek or minimalDays.386*/387@java.io.Serial388private Object readResolve() throws InvalidObjectException {389try {390return WeekFields.of(firstDayOfWeek, minimalDays);391} catch (IllegalArgumentException iae) {392throw new InvalidObjectException("Invalid serialized WeekFields: " + iae.getMessage());393}394}395396//-----------------------------------------------------------------------397/**398* Gets the first day-of-week.399* <p>400* The first day-of-week varies by culture.401* For example, the US uses Sunday, while France and the ISO-8601 standard use Monday.402* This method returns the first day using the standard {@code DayOfWeek} enum.403*404* @return the first day-of-week, not null405*/406public DayOfWeek getFirstDayOfWeek() {407return firstDayOfWeek;408}409410/**411* Gets the minimal number of days in the first week.412* <p>413* The number of days considered to define the first week of a month or year414* varies by culture.415* For example, the ISO-8601 requires 4 days (more than half a week) to416* be present before counting the first week.417*418* @return the minimal number of days in the first week of a month or year, from 1 to 7419*/420public int getMinimalDaysInFirstWeek() {421return minimalDays;422}423424//-----------------------------------------------------------------------425/**426* Returns a field to access the day of week based on this {@code WeekFields}.427* <p>428* This is similar to {@link ChronoField#DAY_OF_WEEK} but uses values for429* the day-of-week based on this {@code WeekFields}.430* The days are numbered from 1 to 7 where the431* {@link #getFirstDayOfWeek() first day-of-week} is assigned the value 1.432* <p>433* For example, if the first day-of-week is Sunday, then that will have the434* value 1, with other days ranging from Monday as 2 to Saturday as 7.435* <p>436* In the resolving phase of parsing, a localized day-of-week will be converted437* to a standardized {@code ChronoField} day-of-week.438* The day-of-week must be in the valid range 1 to 7.439* Other fields in this class build dates using the standardized day-of-week.440*441* @return a field providing access to the day-of-week with localized numbering, not null442*/443public TemporalField dayOfWeek() {444return dayOfWeek;445}446447/**448* Returns a field to access the week of month based on this {@code WeekFields}.449* <p>450* This represents the concept of the count of weeks within the month where weeks451* start on a fixed day-of-week, such as Monday.452* This field is typically used with {@link WeekFields#dayOfWeek()}.453* <p>454* Week one (1) is the week starting on the {@link WeekFields#getFirstDayOfWeek}455* where there are at least {@link WeekFields#getMinimalDaysInFirstWeek()} days in the month.456* Thus, week one may start up to {@code minDays} days before the start of the month.457* If the first week starts after the start of the month then the period before is week zero (0).458* <p>459* For example:<br>460* - if the 1st day of the month is a Monday, week one starts on the 1st and there is no week zero<br>461* - if the 2nd day of the month is a Monday, week one starts on the 2nd and the 1st is in week zero<br>462* - 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>463* - 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>464* <p>465* This field can be used with any calendar system.466* <p>467* In the resolving phase of parsing, a date can be created from a year,468* week-of-month, month-of-year and day-of-week.469* <p>470* In {@linkplain ResolverStyle#STRICT strict mode}, all four fields are471* validated against their range of valid values. The week-of-month field472* is validated to ensure that the resulting month is the month requested.473* <p>474* In {@linkplain ResolverStyle#SMART smart mode}, all four fields are475* validated against their range of valid values. The week-of-month field476* is validated from 0 to 6, meaning that the resulting date can be in a477* different month to that specified.478* <p>479* In {@linkplain ResolverStyle#LENIENT lenient mode}, the year and day-of-week480* are validated against the range of valid values. The resulting date is calculated481* equivalent to the following four stage approach.482* First, create a date on the first day of the first week of January in the requested year.483* Then take the month-of-year, subtract one, and add the amount in months to the date.484* Then take the week-of-month, subtract one, and add the amount in weeks to the date.485* Finally, adjust to the correct day-of-week within the localized week.486*487* @return a field providing access to the week-of-month, not null488*/489public TemporalField weekOfMonth() {490return weekOfMonth;491}492493/**494* Returns a field to access the week of year based on this {@code WeekFields}.495* <p>496* This represents the concept of the count of weeks within the year where weeks497* start on a fixed day-of-week, such as Monday.498* This field is typically used with {@link WeekFields#dayOfWeek()}.499* <p>500* Week one(1) is the week starting on the {@link WeekFields#getFirstDayOfWeek}501* where there are at least {@link WeekFields#getMinimalDaysInFirstWeek()} days in the year.502* Thus, week one may start up to {@code minDays} days before the start of the year.503* If the first week starts after the start of the year then the period before is week zero (0).504* <p>505* For example:<br>506* - if the 1st day of the year is a Monday, week one starts on the 1st and there is no week zero<br>507* - if the 2nd day of the year is a Monday, week one starts on the 2nd and the 1st is in week zero<br>508* - 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>509* - 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>510* <p>511* This field can be used with any calendar system.512* <p>513* In the resolving phase of parsing, a date can be created from a year,514* week-of-year and day-of-week.515* <p>516* In {@linkplain ResolverStyle#STRICT strict mode}, all three fields are517* validated against their range of valid values. The week-of-year field518* is validated to ensure that the resulting year is the year requested.519* <p>520* In {@linkplain ResolverStyle#SMART smart mode}, all three fields are521* validated against their range of valid values. The week-of-year field522* is validated from 0 to 54, meaning that the resulting date can be in a523* different year to that specified.524* <p>525* In {@linkplain ResolverStyle#LENIENT lenient mode}, the year and day-of-week526* are validated against the range of valid values. The resulting date is calculated527* equivalent to the following three stage approach.528* First, create a date on the first day of the first week in the requested year.529* Then take the week-of-year, subtract one, and add the amount in weeks to the date.530* Finally, adjust to the correct day-of-week within the localized week.531*532* @return a field providing access to the week-of-year, not null533*/534public TemporalField weekOfYear() {535return weekOfYear;536}537538/**539* Returns a field to access the week of a week-based-year based on this {@code WeekFields}.540* <p>541* This represents the concept of the count of weeks within the year where weeks542* start on a fixed day-of-week, such as Monday and each week belongs to exactly one year.543* This field is typically used with {@link WeekFields#dayOfWeek()} and544* {@link WeekFields#weekBasedYear()}.545* <p>546* Week one(1) is the week starting on the {@link WeekFields#getFirstDayOfWeek}547* where there are at least {@link WeekFields#getMinimalDaysInFirstWeek()} days in the year.548* If the first week starts after the start of the year then the period before549* is in the last week of the previous year.550* <p>551* For example:<br>552* - if the 1st day of the year is a Monday, week one starts on the 1st<br>553* - if the 2nd day of the year is a Monday, week one starts on the 2nd and554* the 1st is in the last week of the previous year<br>555* - if the 4th day of the year is a Monday, week one starts on the 4th and556* the 1st to 3rd is in the last week of the previous year<br>557* - if the 5th day of the year is a Monday, week two starts on the 5th and558* the 1st to 4th is in week one<br>559* <p>560* This field can be used with any calendar system.561* <p>562* In the resolving phase of parsing, a date can be created from a week-based-year,563* week-of-year and day-of-week.564* <p>565* In {@linkplain ResolverStyle#STRICT strict mode}, all three fields are566* validated against their range of valid values. The week-of-year field567* is validated to ensure that the resulting week-based-year is the568* week-based-year requested.569* <p>570* In {@linkplain ResolverStyle#SMART smart mode}, all three fields are571* validated against their range of valid values. The week-of-week-based-year field572* is validated from 1 to 53, meaning that the resulting date can be in the573* following week-based-year to that specified.574* <p>575* In {@linkplain ResolverStyle#LENIENT lenient mode}, the year and day-of-week576* are validated against the range of valid values. The resulting date is calculated577* equivalent to the following three stage approach.578* First, create a date on the first day of the first week in the requested week-based-year.579* Then take the week-of-week-based-year, subtract one, and add the amount in weeks to the date.580* Finally, adjust to the correct day-of-week within the localized week.581*582* @return a field providing access to the week-of-week-based-year, not null583*/584public TemporalField weekOfWeekBasedYear() {585return weekOfWeekBasedYear;586}587588/**589* Returns a field to access the year of a week-based-year based on this {@code WeekFields}.590* <p>591* This represents the concept of the year where weeks start on a fixed day-of-week,592* such as Monday and each week belongs to exactly one year.593* This field is typically used with {@link WeekFields#dayOfWeek()} and594* {@link WeekFields#weekOfWeekBasedYear()}.595* <p>596* Week one(1) is the week starting on the {@link WeekFields#getFirstDayOfWeek}597* where there are at least {@link WeekFields#getMinimalDaysInFirstWeek()} days in the year.598* Thus, week one may start before the start of the year.599* If the first week starts after the start of the year then the period before600* is in the last week of the previous year.601* <p>602* This field can be used with any calendar system.603* <p>604* In the resolving phase of parsing, a date can be created from a week-based-year,605* week-of-year and day-of-week.606* <p>607* In {@linkplain ResolverStyle#STRICT strict mode}, all three fields are608* validated against their range of valid values. The week-of-year field609* is validated to ensure that the resulting week-based-year is the610* week-based-year requested.611* <p>612* In {@linkplain ResolverStyle#SMART smart mode}, all three fields are613* validated against their range of valid values. The week-of-week-based-year field614* is validated from 1 to 53, meaning that the resulting date can be in the615* following week-based-year to that specified.616* <p>617* In {@linkplain ResolverStyle#LENIENT lenient mode}, the year and day-of-week618* are validated against the range of valid values. The resulting date is calculated619* equivalent to the following three stage approach.620* First, create a date on the first day of the first week in the requested week-based-year.621* Then take the week-of-week-based-year, subtract one, and add the amount in weeks to the date.622* Finally, adjust to the correct day-of-week within the localized week.623*624* @return a field providing access to the week-based-year, not null625*/626public TemporalField weekBasedYear() {627return weekBasedYear;628}629630//-----------------------------------------------------------------------631/**632* Checks if this {@code WeekFields} is equal to the specified object.633* <p>634* The comparison is based on the entire state of the rules, which is635* the first day-of-week and minimal days.636*637* @param object the other rules to compare to, null returns false638* @return true if this is equal to the specified rules639*/640@Override641public boolean equals(Object object) {642if (this == object) {643return true;644}645if (object instanceof WeekFields) {646return hashCode() == object.hashCode();647}648return false;649}650651/**652* A hash code for this {@code WeekFields}.653*654* @return a suitable hash code655*/656@Override657public int hashCode() {658return firstDayOfWeek.ordinal() * 7 + minimalDays;659}660661//-----------------------------------------------------------------------662/**663* A string representation of this {@code WeekFields} instance.664*665* @return the string representation, not null666*/667@Override668public String toString() {669return "WeekFields[" + firstDayOfWeek + ',' + minimalDays + ']';670}671672//-----------------------------------------------------------------------673/**674* Field type that computes DayOfWeek, WeekOfMonth, and WeekOfYear675* based on a WeekFields.676* A separate Field instance is required for each different WeekFields;677* combination of start of week and minimum number of days.678* Constructors are provided to create fields for DayOfWeek, WeekOfMonth,679* and WeekOfYear.680*/681static class ComputedDayOfField implements TemporalField {682683/**684* Returns a field to access the day of week,685* computed based on a WeekFields.686* <p>687* The WeekDefintion of the first day of the week is used with688* the ISO DAY_OF_WEEK field to compute week boundaries.689*/690static ComputedDayOfField ofDayOfWeekField(WeekFields weekDef) {691return new ComputedDayOfField("DayOfWeek", weekDef, DAYS, WEEKS, DAY_OF_WEEK_RANGE);692}693694/**695* Returns a field to access the week of month,696* computed based on a WeekFields.697* @see WeekFields#weekOfMonth()698*/699static ComputedDayOfField ofWeekOfMonthField(WeekFields weekDef) {700return new ComputedDayOfField("WeekOfMonth", weekDef, WEEKS, MONTHS, WEEK_OF_MONTH_RANGE);701}702703/**704* Returns a field to access the week of year,705* computed based on a WeekFields.706* @see WeekFields#weekOfYear()707*/708static ComputedDayOfField ofWeekOfYearField(WeekFields weekDef) {709return new ComputedDayOfField("WeekOfYear", weekDef, WEEKS, YEARS, WEEK_OF_YEAR_RANGE);710}711712/**713* Returns a field to access the week of week-based-year,714* computed based on a WeekFields.715* @see WeekFields#weekOfWeekBasedYear()716*/717static ComputedDayOfField ofWeekOfWeekBasedYearField(WeekFields weekDef) {718return new ComputedDayOfField("WeekOfWeekBasedYear", weekDef, WEEKS, IsoFields.WEEK_BASED_YEARS, WEEK_OF_WEEK_BASED_YEAR_RANGE);719}720721/**722* Returns a field to access the week of week-based-year,723* computed based on a WeekFields.724* @see WeekFields#weekBasedYear()725*/726static ComputedDayOfField ofWeekBasedYearField(WeekFields weekDef) {727return new ComputedDayOfField("WeekBasedYear", weekDef, IsoFields.WEEK_BASED_YEARS, FOREVER, ChronoField.YEAR.range());728}729730/**731* Return a new week-based-year date of the Chronology, year, week-of-year,732* and dow of week.733* @param chrono The chronology of the new date734* @param yowby the year of the week-based-year735* @param wowby the week of the week-based-year736* @param dow the day of the week737* @return a ChronoLocalDate for the requested year, week of year, and day of week738*/739private ChronoLocalDate ofWeekBasedYear(Chronology chrono,740int yowby, int wowby, int dow) {741ChronoLocalDate date = chrono.date(yowby, 1, 1);742int ldow = localizedDayOfWeek(date);743int offset = startOfWeekOffset(1, ldow);744745// Clamp the week of year to keep it in the same year746int yearLen = date.lengthOfYear();747int newYearWeek = computeWeek(offset, yearLen + weekDef.getMinimalDaysInFirstWeek());748wowby = Math.min(wowby, newYearWeek - 1);749750int days = -offset + (dow - 1) + (wowby - 1) * 7;751return date.plus(days, DAYS);752}753754private final String name;755private final WeekFields weekDef;756private final TemporalUnit baseUnit;757private final TemporalUnit rangeUnit;758private final ValueRange range;759760private ComputedDayOfField(String name, WeekFields weekDef, TemporalUnit baseUnit, TemporalUnit rangeUnit, ValueRange range) {761this.name = name;762this.weekDef = weekDef;763this.baseUnit = baseUnit;764this.rangeUnit = rangeUnit;765this.range = range;766}767768private static final ValueRange DAY_OF_WEEK_RANGE = ValueRange.of(1, 7);769private static final ValueRange WEEK_OF_MONTH_RANGE = ValueRange.of(0, 1, 4, 6);770private static final ValueRange WEEK_OF_YEAR_RANGE = ValueRange.of(0, 1, 52, 54);771private static final ValueRange WEEK_OF_WEEK_BASED_YEAR_RANGE = ValueRange.of(1, 52, 53);772773@Override774public long getFrom(TemporalAccessor temporal) {775if (rangeUnit == WEEKS) { // day-of-week776return localizedDayOfWeek(temporal);777} else if (rangeUnit == MONTHS) { // week-of-month778return localizedWeekOfMonth(temporal);779} else if (rangeUnit == YEARS) { // week-of-year780return localizedWeekOfYear(temporal);781} else if (rangeUnit == WEEK_BASED_YEARS) {782return localizedWeekOfWeekBasedYear(temporal);783} else if (rangeUnit == FOREVER) {784return localizedWeekBasedYear(temporal);785} else {786throw new IllegalStateException("unreachable, rangeUnit: " + rangeUnit + ", this: " + this);787}788}789790private int localizedDayOfWeek(TemporalAccessor temporal) {791int sow = weekDef.getFirstDayOfWeek().getValue();792int isoDow = temporal.get(DAY_OF_WEEK);793return Math.floorMod(isoDow - sow, 7) + 1;794}795796private int localizedDayOfWeek(int isoDow) {797int sow = weekDef.getFirstDayOfWeek().getValue();798return Math.floorMod(isoDow - sow, 7) + 1;799}800801private long localizedWeekOfMonth(TemporalAccessor temporal) {802int dow = localizedDayOfWeek(temporal);803int dom = temporal.get(DAY_OF_MONTH);804int offset = startOfWeekOffset(dom, dow);805return computeWeek(offset, dom);806}807808private long localizedWeekOfYear(TemporalAccessor temporal) {809int dow = localizedDayOfWeek(temporal);810int doy = temporal.get(DAY_OF_YEAR);811int offset = startOfWeekOffset(doy, dow);812return computeWeek(offset, doy);813}814815/**816* Returns the year of week-based-year for the temporal.817* The year can be the previous year, the current year, or the next year.818* @param temporal a date of any chronology, not null819* @return the year of week-based-year for the date820*/821private int localizedWeekBasedYear(TemporalAccessor temporal) {822int dow = localizedDayOfWeek(temporal);823int year = temporal.get(YEAR);824int doy = temporal.get(DAY_OF_YEAR);825int offset = startOfWeekOffset(doy, dow);826int week = computeWeek(offset, doy);827if (week == 0) {828// Day is in end of week of previous year; return the previous year829return year - 1;830} else {831// If getting close to end of year, use higher precision logic832// Check if date of year is in partial week associated with next year833ValueRange dayRange = temporal.range(DAY_OF_YEAR);834int yearLen = (int)dayRange.getMaximum();835int newYearWeek = computeWeek(offset, yearLen + weekDef.getMinimalDaysInFirstWeek());836if (week >= newYearWeek) {837return year + 1;838}839}840return year;841}842843/**844* Returns the week of week-based-year for the temporal.845* The week can be part of the previous year, the current year,846* or the next year depending on the week start and minimum number847* of days.848* @param temporal a date of any chronology849* @return the week of the year850* @see #localizedWeekBasedYear(java.time.temporal.TemporalAccessor)851*/852private int localizedWeekOfWeekBasedYear(TemporalAccessor temporal) {853int dow = localizedDayOfWeek(temporal);854int doy = temporal.get(DAY_OF_YEAR);855int offset = startOfWeekOffset(doy, dow);856int week = computeWeek(offset, doy);857if (week == 0) {858// Day is in end of week of previous year859// Recompute from the last day of the previous year860ChronoLocalDate date = Chronology.from(temporal).date(temporal);861date = date.minus(doy, DAYS); // Back down into previous year862return localizedWeekOfWeekBasedYear(date);863} else if (week > 50) {864// If getting close to end of year, use higher precision logic865// Check if date of year is in partial week associated with next year866ValueRange dayRange = temporal.range(DAY_OF_YEAR);867int yearLen = (int)dayRange.getMaximum();868int newYearWeek = computeWeek(offset, yearLen + weekDef.getMinimalDaysInFirstWeek());869if (week >= newYearWeek) {870// Overlaps with week of following year; reduce to week in following year871week = week - newYearWeek + 1;872}873}874return week;875}876877/**878* Returns an offset to align week start with a day of month or day of year.879*880* @param day the day; 1 through infinity881* @param dow the day of the week of that day; 1 through 7882* @return an offset in days to align a day with the start of the first 'full' week883*/884private int startOfWeekOffset(int day, int dow) {885// offset of first day corresponding to the day of week in first 7 days (zero origin)886int weekStart = Math.floorMod(day - dow, 7);887int offset = -weekStart;888if (weekStart + 1 > weekDef.getMinimalDaysInFirstWeek()) {889// The previous week has the minimum days in the current month to be a 'week'890offset = 7 - weekStart;891}892return offset;893}894895/**896* Returns the week number computed from the reference day and reference dayOfWeek.897*898* @param offset the offset to align a date with the start of week899* from {@link #startOfWeekOffset}.900* @param day the day for which to compute the week number901* @return the week number where zero is used for a partial week and 1 for the first full week902*/903private int computeWeek(int offset, int day) {904return ((7 + offset + (day - 1)) / 7);905}906907@SuppressWarnings("unchecked")908@Override909public <R extends Temporal> R adjustInto(R temporal, long newValue) {910// Check the new value and get the old value of the field911int newVal = range.checkValidIntValue(newValue, this); // lenient check range912int currentVal = temporal.get(this);913if (newVal == currentVal) {914return temporal;915}916917if (rangeUnit == FOREVER) { // replace year of WeekBasedYear918// Create a new date object with the same chronology,919// the desired year and the same week and dow.920int idow = temporal.get(weekDef.dayOfWeek);921int wowby = temporal.get(weekDef.weekOfWeekBasedYear);922return (R) ofWeekBasedYear(Chronology.from(temporal), (int)newValue, wowby, idow);923} else {924// Compute the difference and add that using the base unit of the field925return (R) temporal.plus(newVal - currentVal, baseUnit);926}927}928929@Override930public ChronoLocalDate resolve(931Map<TemporalField, Long> fieldValues, TemporalAccessor partialTemporal, ResolverStyle resolverStyle) {932final long value = fieldValues.get(this);933final int newValue = Math.toIntExact(value); // broad limit makes overflow checking lighter934// first convert localized day-of-week to ISO day-of-week935// doing this first handles case where both ISO and localized were parsed and might mismatch936// day-of-week is always strict as two different day-of-week values makes lenient complex937if (rangeUnit == WEEKS) { // day-of-week938final int checkedValue = range.checkValidIntValue(value, this); // no leniency as too complex939final int startDow = weekDef.getFirstDayOfWeek().getValue();940long isoDow = Math.floorMod((startDow - 1) + (checkedValue - 1), 7) + 1;941fieldValues.remove(this);942fieldValues.put(DAY_OF_WEEK, isoDow);943return null;944}945946// can only build date if ISO day-of-week is present947if (fieldValues.containsKey(DAY_OF_WEEK) == false) {948return null;949}950int isoDow = DAY_OF_WEEK.checkValidIntValue(fieldValues.get(DAY_OF_WEEK));951int dow = localizedDayOfWeek(isoDow);952953// build date954Chronology chrono = Chronology.from(partialTemporal);955if (fieldValues.containsKey(YEAR)) {956int year = YEAR.checkValidIntValue(fieldValues.get(YEAR)); // validate957if (rangeUnit == MONTHS && fieldValues.containsKey(MONTH_OF_YEAR)) { // week-of-month958long month = fieldValues.get(MONTH_OF_YEAR); // not validated yet959return resolveWoM(fieldValues, chrono, year, month, newValue, dow, resolverStyle);960}961if (rangeUnit == YEARS) { // week-of-year962return resolveWoY(fieldValues, chrono, year, newValue, dow, resolverStyle);963}964} else if ((rangeUnit == WEEK_BASED_YEARS || rangeUnit == FOREVER) &&965fieldValues.containsKey(weekDef.weekBasedYear) &&966fieldValues.containsKey(weekDef.weekOfWeekBasedYear)) { // week-of-week-based-year and year-of-week-based-year967return resolveWBY(fieldValues, chrono, dow, resolverStyle);968}969return null;970}971972private ChronoLocalDate resolveWoM(973Map<TemporalField, Long> fieldValues, Chronology chrono, int year, long month, long wom, int localDow, ResolverStyle resolverStyle) {974ChronoLocalDate date;975if (resolverStyle == ResolverStyle.LENIENT) {976date = chrono.date(year, 1, 1).plus(Math.subtractExact(month, 1), MONTHS);977long weeks = Math.subtractExact(wom, localizedWeekOfMonth(date));978int days = localDow - localizedDayOfWeek(date); // safe from overflow979date = date.plus(Math.addExact(Math.multiplyExact(weeks, 7), days), DAYS);980} else {981int monthValid = MONTH_OF_YEAR.checkValidIntValue(month); // validate982date = chrono.date(year, monthValid, 1);983int womInt = range.checkValidIntValue(wom, this); // validate984int weeks = (int) (womInt - localizedWeekOfMonth(date)); // safe from overflow985int days = localDow - localizedDayOfWeek(date); // safe from overflow986date = date.plus(weeks * 7 + days, DAYS);987if (resolverStyle == ResolverStyle.STRICT && date.getLong(MONTH_OF_YEAR) != month) {988throw new DateTimeException("Strict mode rejected resolved date as it is in a different month");989}990}991fieldValues.remove(this);992fieldValues.remove(YEAR);993fieldValues.remove(MONTH_OF_YEAR);994fieldValues.remove(DAY_OF_WEEK);995return date;996}997998private ChronoLocalDate resolveWoY(999Map<TemporalField, Long> fieldValues, Chronology chrono, int year, long woy, int localDow, ResolverStyle resolverStyle) {1000ChronoLocalDate date = chrono.date(year, 1, 1);1001if (resolverStyle == ResolverStyle.LENIENT) {1002long weeks = Math.subtractExact(woy, localizedWeekOfYear(date));1003int days = localDow - localizedDayOfWeek(date); // safe from overflow1004date = date.plus(Math.addExact(Math.multiplyExact(weeks, 7), days), DAYS);1005} else {1006int womInt = range.checkValidIntValue(woy, this); // validate1007int weeks = (int) (womInt - localizedWeekOfYear(date)); // safe from overflow1008int days = localDow - localizedDayOfWeek(date); // safe from overflow1009date = date.plus(weeks * 7 + days, DAYS);1010if (resolverStyle == ResolverStyle.STRICT && date.getLong(YEAR) != year) {1011throw new DateTimeException("Strict mode rejected resolved date as it is in a different year");1012}1013}1014fieldValues.remove(this);1015fieldValues.remove(YEAR);1016fieldValues.remove(DAY_OF_WEEK);1017return date;1018}10191020private ChronoLocalDate resolveWBY(1021Map<TemporalField, Long> fieldValues, Chronology chrono, int localDow, ResolverStyle resolverStyle) {1022int yowby = weekDef.weekBasedYear.range().checkValidIntValue(1023fieldValues.get(weekDef.weekBasedYear), weekDef.weekBasedYear);1024ChronoLocalDate date;1025if (resolverStyle == ResolverStyle.LENIENT) {1026date = ofWeekBasedYear(chrono, yowby, 1, localDow);1027long wowby = fieldValues.get(weekDef.weekOfWeekBasedYear);1028long weeks = Math.subtractExact(wowby, 1);1029date = date.plus(weeks, WEEKS);1030} else {1031int wowby = weekDef.weekOfWeekBasedYear.range().checkValidIntValue(1032fieldValues.get(weekDef.weekOfWeekBasedYear), weekDef.weekOfWeekBasedYear); // validate1033date = ofWeekBasedYear(chrono, yowby, wowby, localDow);1034if (resolverStyle == ResolverStyle.STRICT && localizedWeekBasedYear(date) != yowby) {1035throw new DateTimeException("Strict mode rejected resolved date as it is in a different week-based-year");1036}1037}1038fieldValues.remove(this);1039fieldValues.remove(weekDef.weekBasedYear);1040fieldValues.remove(weekDef.weekOfWeekBasedYear);1041fieldValues.remove(DAY_OF_WEEK);1042return date;1043}10441045//-----------------------------------------------------------------------1046@Override1047public String getDisplayName(Locale locale) {1048Objects.requireNonNull(locale, "locale");1049if (rangeUnit == YEARS) { // only have values for week-of-year1050LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased()1051.getLocaleResources(1052CalendarDataUtility.findRegionOverride(locale));1053ResourceBundle rb = lr.getJavaTimeFormatData();1054return rb.containsKey("field.week") ? rb.getString("field.week") : name;1055}1056return name;1057}10581059@Override1060public TemporalUnit getBaseUnit() {1061return baseUnit;1062}10631064@Override1065public TemporalUnit getRangeUnit() {1066return rangeUnit;1067}10681069@Override1070public boolean isDateBased() {1071return true;1072}10731074@Override1075public boolean isTimeBased() {1076return false;1077}10781079@Override1080public ValueRange range() {1081return range;1082}10831084//-----------------------------------------------------------------------1085@Override1086public boolean isSupportedBy(TemporalAccessor temporal) {1087if (temporal.isSupported(DAY_OF_WEEK)) {1088if (rangeUnit == WEEKS) { // day-of-week1089return true;1090} else if (rangeUnit == MONTHS) { // week-of-month1091return temporal.isSupported(DAY_OF_MONTH);1092} else if (rangeUnit == YEARS) { // week-of-year1093return temporal.isSupported(DAY_OF_YEAR);1094} else if (rangeUnit == WEEK_BASED_YEARS) {1095return temporal.isSupported(DAY_OF_YEAR);1096} else if (rangeUnit == FOREVER) {1097return temporal.isSupported(YEAR);1098}1099}1100return false;1101}11021103@Override1104public ValueRange rangeRefinedBy(TemporalAccessor temporal) {1105if (rangeUnit == ChronoUnit.WEEKS) { // day-of-week1106return range;1107} else if (rangeUnit == MONTHS) { // week-of-month1108return rangeByWeek(temporal, DAY_OF_MONTH);1109} else if (rangeUnit == YEARS) { // week-of-year1110return rangeByWeek(temporal, DAY_OF_YEAR);1111} else if (rangeUnit == WEEK_BASED_YEARS) {1112return rangeWeekOfWeekBasedYear(temporal);1113} else if (rangeUnit == FOREVER) {1114return YEAR.range();1115} else {1116throw new IllegalStateException("unreachable, rangeUnit: " + rangeUnit + ", this: " + this);1117}1118}11191120/**1121* Map the field range to a week range1122* @param temporal the temporal1123* @param field the field to get the range of1124* @return the ValueRange with the range adjusted to weeks.1125*/1126private ValueRange rangeByWeek(TemporalAccessor temporal, TemporalField field) {1127int dow = localizedDayOfWeek(temporal);1128int offset = startOfWeekOffset(temporal.get(field), dow);1129ValueRange fieldRange = temporal.range(field);1130return ValueRange.of(computeWeek(offset, (int) fieldRange.getMinimum()),1131computeWeek(offset, (int) fieldRange.getMaximum()));1132}11331134/**1135* Map the field range to a week range of a week year.1136* @param temporal the temporal1137* @return the ValueRange with the range adjusted to weeks.1138*/1139private ValueRange rangeWeekOfWeekBasedYear(TemporalAccessor temporal) {1140if (!temporal.isSupported(DAY_OF_YEAR)) {1141return WEEK_OF_YEAR_RANGE;1142}1143int dow = localizedDayOfWeek(temporal);1144int doy = temporal.get(DAY_OF_YEAR);1145int offset = startOfWeekOffset(doy, dow);1146int week = computeWeek(offset, doy);1147if (week == 0) {1148// Day is in end of week of previous year1149// Recompute from the last day of the previous year1150ChronoLocalDate date = Chronology.from(temporal).date(temporal);1151date = date.minus(doy + 7, DAYS); // Back down into previous year1152return rangeWeekOfWeekBasedYear(date);1153}1154// Check if day of year is in partial week associated with next year1155ValueRange dayRange = temporal.range(DAY_OF_YEAR);1156int yearLen = (int)dayRange.getMaximum();1157int newYearWeek = computeWeek(offset, yearLen + weekDef.getMinimalDaysInFirstWeek());11581159if (week >= newYearWeek) {1160// Overlaps with weeks of following year; recompute from a week in following year1161ChronoLocalDate date = Chronology.from(temporal).date(temporal);1162date = date.plus(yearLen - doy + 1 + 7, ChronoUnit.DAYS);1163return rangeWeekOfWeekBasedYear(date);1164}1165return ValueRange.of(1, newYearWeek-1);1166}11671168//-----------------------------------------------------------------------1169@Override1170public String toString() {1171return name + "[" + weekDef.toString() + "]";1172}1173}1174}117511761177