Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/chrono/IsoChronology.java
38918 views
/*1* Copyright (c) 2012, 2015, 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) 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.chrono;6263import java.io.InvalidObjectException;64import static java.time.temporal.ChronoField.DAY_OF_MONTH;65import static java.time.temporal.ChronoField.ERA;66import static java.time.temporal.ChronoField.MONTH_OF_YEAR;67import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;68import static java.time.temporal.ChronoField.YEAR;69import static java.time.temporal.ChronoField.YEAR_OF_ERA;7071import java.io.ObjectInputStream;72import java.io.Serializable;73import java.time.Clock;74import java.time.DateTimeException;75import java.time.Instant;76import java.time.LocalDate;77import java.time.LocalDateTime;78import java.time.Month;79import java.time.Period;80import java.time.Year;81import java.time.ZoneId;82import java.time.ZonedDateTime;83import java.time.format.ResolverStyle;84import java.time.temporal.ChronoField;85import java.time.temporal.TemporalAccessor;86import java.time.temporal.TemporalField;87import java.time.temporal.ValueRange;88import java.util.Arrays;89import java.util.List;90import java.util.Locale;91import java.util.Map;92import java.util.Objects;9394/**95* The ISO calendar system.96* <p>97* This chronology defines the rules of the ISO calendar system.98* This calendar system is based on the ISO-8601 standard, which is the99* <i>de facto</i> world calendar.100* <p>101* The fields are defined as follows:102* <ul>103* <li>era - There are two eras, 'Current Era' (CE) and 'Before Current Era' (BCE).104* <li>year-of-era - The year-of-era is the same as the proleptic-year for the current CE era.105* For the BCE era before the ISO epoch the year increases from 1 upwards as time goes backwards.106* <li>proleptic-year - The proleptic year is the same as the year-of-era for the107* current era. For the previous era, years have zero, then negative values.108* <li>month-of-year - There are 12 months in an ISO year, numbered from 1 to 12.109* <li>day-of-month - There are between 28 and 31 days in each of the ISO month, numbered from 1 to 31.110* Months 4, 6, 9 and 11 have 30 days, Months 1, 3, 5, 7, 8, 10 and 12 have 31 days.111* Month 2 has 28 days, or 29 in a leap year.112* <li>day-of-year - There are 365 days in a standard ISO year and 366 in a leap year.113* The days are numbered from 1 to 365 or 1 to 366.114* <li>leap-year - Leap years occur every 4 years, except where the year is divisble by 100 and not divisble by 400.115* </ul>116*117* @implSpec118* This class is immutable and thread-safe.119*120* @since 1.8121*/122public final class IsoChronology extends AbstractChronology implements Serializable {123124/**125* Singleton instance of the ISO chronology.126*/127public static final IsoChronology INSTANCE = new IsoChronology();128129/**130* Serialization version.131*/132private static final long serialVersionUID = -1440403870442975015L;133134/**135* Restricted constructor.136*/137private IsoChronology() {138}139140//-----------------------------------------------------------------------141/**142* Gets the ID of the chronology - 'ISO'.143* <p>144* The ID uniquely identifies the {@code Chronology}.145* It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.146*147* @return the chronology ID - 'ISO'148* @see #getCalendarType()149*/150@Override151public String getId() {152return "ISO";153}154155/**156* Gets the calendar type of the underlying calendar system - 'iso8601'.157* <p>158* The calendar type is an identifier defined by the159* <em>Unicode Locale Data Markup Language (LDML)</em> specification.160* It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.161* It can also be used as part of a locale, accessible via162* {@link Locale#getUnicodeLocaleType(String)} with the key 'ca'.163*164* @return the calendar system type - 'iso8601'165* @see #getId()166*/167@Override168public String getCalendarType() {169return "iso8601";170}171172//-----------------------------------------------------------------------173/**174* Obtains an ISO local date from the era, year-of-era, month-of-year175* and day-of-month fields.176*177* @param era the ISO era, not null178* @param yearOfEra the ISO year-of-era179* @param month the ISO month-of-year180* @param dayOfMonth the ISO day-of-month181* @return the ISO local date, not null182* @throws DateTimeException if unable to create the date183* @throws ClassCastException if the type of {@code era} is not {@code IsoEra}184*/185@Override // override with covariant return type186public LocalDate date(Era era, int yearOfEra, int month, int dayOfMonth) {187return date(prolepticYear(era, yearOfEra), month, dayOfMonth);188}189190/**191* Obtains an ISO local date from the proleptic-year, month-of-year192* and day-of-month fields.193* <p>194* This is equivalent to {@link LocalDate#of(int, int, int)}.195*196* @param prolepticYear the ISO proleptic-year197* @param month the ISO month-of-year198* @param dayOfMonth the ISO day-of-month199* @return the ISO local date, not null200* @throws DateTimeException if unable to create the date201*/202@Override // override with covariant return type203public LocalDate date(int prolepticYear, int month, int dayOfMonth) {204return LocalDate.of(prolepticYear, month, dayOfMonth);205}206207/**208* Obtains an ISO local date from the era, year-of-era and day-of-year fields.209*210* @param era the ISO era, not null211* @param yearOfEra the ISO year-of-era212* @param dayOfYear the ISO day-of-year213* @return the ISO local date, not null214* @throws DateTimeException if unable to create the date215*/216@Override // override with covariant return type217public LocalDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {218return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);219}220221/**222* Obtains an ISO local date from the proleptic-year and day-of-year fields.223* <p>224* This is equivalent to {@link LocalDate#ofYearDay(int, int)}.225*226* @param prolepticYear the ISO proleptic-year227* @param dayOfYear the ISO day-of-year228* @return the ISO local date, not null229* @throws DateTimeException if unable to create the date230*/231@Override // override with covariant return type232public LocalDate dateYearDay(int prolepticYear, int dayOfYear) {233return LocalDate.ofYearDay(prolepticYear, dayOfYear);234}235236/**237* Obtains an ISO local date from the epoch-day.238* <p>239* This is equivalent to {@link LocalDate#ofEpochDay(long)}.240*241* @param epochDay the epoch day242* @return the ISO local date, not null243* @throws DateTimeException if unable to create the date244*/245@Override // override with covariant return type246public LocalDate dateEpochDay(long epochDay) {247return LocalDate.ofEpochDay(epochDay);248}249250//-----------------------------------------------------------------------251/**252* Obtains an ISO local date from another date-time object.253* <p>254* This is equivalent to {@link LocalDate#from(TemporalAccessor)}.255*256* @param temporal the date-time object to convert, not null257* @return the ISO local date, not null258* @throws DateTimeException if unable to create the date259*/260@Override // override with covariant return type261public LocalDate date(TemporalAccessor temporal) {262return LocalDate.from(temporal);263}264265/**266* Obtains an ISO local date-time from another date-time object.267* <p>268* This is equivalent to {@link LocalDateTime#from(TemporalAccessor)}.269*270* @param temporal the date-time object to convert, not null271* @return the ISO local date-time, not null272* @throws DateTimeException if unable to create the date-time273*/274@Override // override with covariant return type275public LocalDateTime localDateTime(TemporalAccessor temporal) {276return LocalDateTime.from(temporal);277}278279/**280* Obtains an ISO zoned date-time from another date-time object.281* <p>282* This is equivalent to {@link ZonedDateTime#from(TemporalAccessor)}.283*284* @param temporal the date-time object to convert, not null285* @return the ISO zoned date-time, not null286* @throws DateTimeException if unable to create the date-time287*/288@Override // override with covariant return type289public ZonedDateTime zonedDateTime(TemporalAccessor temporal) {290return ZonedDateTime.from(temporal);291}292293/**294* Obtains an ISO zoned date-time in this chronology from an {@code Instant}.295* <p>296* This is equivalent to {@link ZonedDateTime#ofInstant(Instant, ZoneId)}.297*298* @param instant the instant to create the date-time from, not null299* @param zone the time-zone, not null300* @return the zoned date-time, not null301* @throws DateTimeException if the result exceeds the supported range302*/303@Override304public ZonedDateTime zonedDateTime(Instant instant, ZoneId zone) {305return ZonedDateTime.ofInstant(instant, zone);306}307308//-----------------------------------------------------------------------309/**310* Obtains the current ISO local date from the system clock in the default time-zone.311* <p>312* This will query the {@link Clock#systemDefaultZone() system clock} in the default313* time-zone to obtain the current date.314* <p>315* Using this method will prevent the ability to use an alternate clock for testing316* because the clock is hard-coded.317*318* @return the current ISO local date using the system clock and default time-zone, not null319* @throws DateTimeException if unable to create the date320*/321@Override // override with covariant return type322public LocalDate dateNow() {323return dateNow(Clock.systemDefaultZone());324}325326/**327* Obtains the current ISO local date from the system clock in the specified time-zone.328* <p>329* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.330* Specifying the time-zone avoids dependence on the default time-zone.331* <p>332* Using this method will prevent the ability to use an alternate clock for testing333* because the clock is hard-coded.334*335* @return the current ISO local date using the system clock, not null336* @throws DateTimeException if unable to create the date337*/338@Override // override with covariant return type339public LocalDate dateNow(ZoneId zone) {340return dateNow(Clock.system(zone));341}342343/**344* Obtains the current ISO local date from the specified clock.345* <p>346* This will query the specified clock to obtain the current date - today.347* Using this method allows the use of an alternate clock for testing.348* The alternate clock may be introduced using {@link Clock dependency injection}.349*350* @param clock the clock to use, not null351* @return the current ISO local date, not null352* @throws DateTimeException if unable to create the date353*/354@Override // override with covariant return type355public LocalDate dateNow(Clock clock) {356Objects.requireNonNull(clock, "clock");357return date(LocalDate.now(clock));358}359360//-----------------------------------------------------------------------361/**362* Checks if the year is a leap year, according to the ISO proleptic363* calendar system rules.364* <p>365* This method applies the current rules for leap years across the whole time-line.366* In general, a year is a leap year if it is divisible by four without367* remainder. However, years divisible by 100, are not leap years, with368* the exception of years divisible by 400 which are.369* <p>370* For example, 1904 is a leap year it is divisible by 4.371* 1900 was not a leap year as it is divisible by 100, however 2000 was a372* leap year as it is divisible by 400.373* <p>374* The calculation is proleptic - applying the same rules into the far future and far past.375* This is historically inaccurate, but is correct for the ISO-8601 standard.376*377* @param prolepticYear the ISO proleptic year to check378* @return true if the year is leap, false otherwise379*/380@Override381public boolean isLeapYear(long prolepticYear) {382return ((prolepticYear & 3) == 0) && ((prolepticYear % 100) != 0 || (prolepticYear % 400) == 0);383}384385@Override386public int prolepticYear(Era era, int yearOfEra) {387if (era instanceof IsoEra == false) {388throw new ClassCastException("Era must be IsoEra");389}390return (era == IsoEra.CE ? yearOfEra : 1 - yearOfEra);391}392393@Override394public IsoEra eraOf(int eraValue) {395return IsoEra.of(eraValue);396}397398@Override399public List<Era> eras() {400return Arrays.<Era>asList(IsoEra.values());401}402403//-----------------------------------------------------------------------404/**405* Resolves parsed {@code ChronoField} values into a date during parsing.406* <p>407* Most {@code TemporalField} implementations are resolved using the408* resolve method on the field. By contrast, the {@code ChronoField} class409* defines fields that only have meaning relative to the chronology.410* As such, {@code ChronoField} date fields are resolved here in the411* context of a specific chronology.412* <p>413* {@code ChronoField} instances on the ISO calendar system are resolved414* as follows.415* <ul>416* <li>{@code EPOCH_DAY} - If present, this is converted to a {@code LocalDate}417* and all other date fields are then cross-checked against the date.418* <li>{@code PROLEPTIC_MONTH} - If present, then it is split into the419* {@code YEAR} and {@code MONTH_OF_YEAR}. If the mode is strict or smart420* then the field is validated.421* <li>{@code YEAR_OF_ERA} and {@code ERA} - If both are present, then they422* are combined to form a {@code YEAR}. In lenient mode, the {@code YEAR_OF_ERA}423* range is not validated, in smart and strict mode it is. The {@code ERA} is424* validated for range in all three modes. If only the {@code YEAR_OF_ERA} is425* present, and the mode is smart or lenient, then the current era (CE/AD)426* is assumed. In strict mode, no era is assumed and the {@code YEAR_OF_ERA} is427* left untouched. If only the {@code ERA} is present, then it is left untouched.428* <li>{@code YEAR}, {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH} -429* If all three are present, then they are combined to form a {@code LocalDate}.430* In all three modes, the {@code YEAR} is validated. If the mode is smart or strict,431* then the month and day are validated, with the day validated from 1 to 31.432* If the mode is lenient, then the date is combined in a manner equivalent to433* creating a date on the first of January in the requested year, then adding434* the difference in months, then the difference in days.435* If the mode is smart, and the day-of-month is greater than the maximum for436* the year-month, then the day-of-month is adjusted to the last day-of-month.437* If the mode is strict, then the three fields must form a valid date.438* <li>{@code YEAR} and {@code DAY_OF_YEAR} -439* If both are present, then they are combined to form a {@code LocalDate}.440* In all three modes, the {@code YEAR} is validated.441* If the mode is lenient, then the date is combined in a manner equivalent to442* creating a date on the first of January in the requested year, then adding443* the difference in days.444* If the mode is smart or strict, then the two fields must form a valid date.445* <li>{@code YEAR}, {@code MONTH_OF_YEAR}, {@code ALIGNED_WEEK_OF_MONTH} and446* {@code ALIGNED_DAY_OF_WEEK_IN_MONTH} -447* If all four are present, then they are combined to form a {@code LocalDate}.448* In all three modes, the {@code YEAR} is validated.449* If the mode is lenient, then the date is combined in a manner equivalent to450* creating a date on the first of January in the requested year, then adding451* the difference in months, then the difference in weeks, then in days.452* If the mode is smart or strict, then the all four fields are validated to453* their outer ranges. The date is then combined in a manner equivalent to454* creating a date on the first day of the requested year and month, then adding455* the amount in weeks and days to reach their values. If the mode is strict,456* the date is additionally validated to check that the day and week adjustment457* did not change the month.458* <li>{@code YEAR}, {@code MONTH_OF_YEAR}, {@code ALIGNED_WEEK_OF_MONTH} and459* {@code DAY_OF_WEEK} - If all four are present, then they are combined to460* form a {@code LocalDate}. The approach is the same as described above for461* years, months and weeks in {@code ALIGNED_DAY_OF_WEEK_IN_MONTH}.462* The day-of-week is adjusted as the next or same matching day-of-week once463* the years, months and weeks have been handled.464* <li>{@code YEAR}, {@code ALIGNED_WEEK_OF_YEAR} and {@code ALIGNED_DAY_OF_WEEK_IN_YEAR} -465* If all three are present, then they are combined to form a {@code LocalDate}.466* In all three modes, the {@code YEAR} is validated.467* If the mode is lenient, then the date is combined in a manner equivalent to468* creating a date on the first of January in the requested year, then adding469* the difference in weeks, then in days.470* If the mode is smart or strict, then the all three fields are validated to471* their outer ranges. The date is then combined in a manner equivalent to472* creating a date on the first day of the requested year, then adding473* the amount in weeks and days to reach their values. If the mode is strict,474* the date is additionally validated to check that the day and week adjustment475* did not change the year.476* <li>{@code YEAR}, {@code ALIGNED_WEEK_OF_YEAR} and {@code DAY_OF_WEEK} -477* If all three are present, then they are combined to form a {@code LocalDate}.478* The approach is the same as described above for years and weeks in479* {@code ALIGNED_DAY_OF_WEEK_IN_YEAR}. The day-of-week is adjusted as the480* next or same matching day-of-week once the years and weeks have been handled.481* </ul>482*483* @param fieldValues the map of fields to values, which can be updated, not null484* @param resolverStyle the requested type of resolve, not null485* @return the resolved date, null if insufficient information to create a date486* @throws DateTimeException if the date cannot be resolved, typically487* because of a conflict in the input data488*/489@Override // override for performance490public LocalDate resolveDate(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {491return (LocalDate) super.resolveDate(fieldValues, resolverStyle);492}493494@Override // override for better proleptic algorithm495void resolveProlepticMonth(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {496Long pMonth = fieldValues.remove(PROLEPTIC_MONTH);497if (pMonth != null) {498if (resolverStyle != ResolverStyle.LENIENT) {499PROLEPTIC_MONTH.checkValidValue(pMonth);500}501addFieldValue(fieldValues, MONTH_OF_YEAR, Math.floorMod(pMonth, 12) + 1);502addFieldValue(fieldValues, YEAR, Math.floorDiv(pMonth, 12));503}504}505506@Override // override for enhanced behaviour507LocalDate resolveYearOfEra(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {508Long yoeLong = fieldValues.remove(YEAR_OF_ERA);509if (yoeLong != null) {510if (resolverStyle != ResolverStyle.LENIENT) {511YEAR_OF_ERA.checkValidValue(yoeLong);512}513Long era = fieldValues.remove(ERA);514if (era == null) {515Long year = fieldValues.get(YEAR);516if (resolverStyle == ResolverStyle.STRICT) {517// do not invent era if strict, but do cross-check with year518if (year != null) {519addFieldValue(fieldValues, YEAR, (year > 0 ? yoeLong: Math.subtractExact(1, yoeLong)));520} else {521// reinstate the field removed earlier, no cross-check issues522fieldValues.put(YEAR_OF_ERA, yoeLong);523}524} else {525// invent era526addFieldValue(fieldValues, YEAR, (year == null || year > 0 ? yoeLong: Math.subtractExact(1, yoeLong)));527}528} else if (era.longValue() == 1L) {529addFieldValue(fieldValues, YEAR, yoeLong);530} else if (era.longValue() == 0L) {531addFieldValue(fieldValues, YEAR, Math.subtractExact(1, yoeLong));532} else {533throw new DateTimeException("Invalid value for era: " + era);534}535} else if (fieldValues.containsKey(ERA)) {536ERA.checkValidValue(fieldValues.get(ERA)); // always validated537}538return null;539}540541@Override // override for performance542LocalDate resolveYMD(Map <TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {543int y = YEAR.checkValidIntValue(fieldValues.remove(YEAR));544if (resolverStyle == ResolverStyle.LENIENT) {545long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);546long days = Math.subtractExact(fieldValues.remove(DAY_OF_MONTH), 1);547return LocalDate.of(y, 1, 1).plusMonths(months).plusDays(days);548}549int moy = MONTH_OF_YEAR.checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR));550int dom = DAY_OF_MONTH.checkValidIntValue(fieldValues.remove(DAY_OF_MONTH));551if (resolverStyle == ResolverStyle.SMART) { // previous valid552if (moy == 4 || moy == 6 || moy == 9 || moy == 11) {553dom = Math.min(dom, 30);554} else if (moy == 2) {555dom = Math.min(dom, Month.FEBRUARY.length(Year.isLeap(y)));556557}558}559return LocalDate.of(y, moy, dom);560}561562//-----------------------------------------------------------------------563@Override564public ValueRange range(ChronoField field) {565return field.range();566}567568//-----------------------------------------------------------------------569/**570* Obtains a period for this chronology based on years, months and days.571* <p>572* This returns a period tied to the ISO chronology using the specified573* years, months and days. See {@link Period} for further details.574*575* @param years the number of years, may be negative576* @param months the number of years, may be negative577* @param days the number of years, may be negative578* @return the period in terms of this chronology, not null579* @return the ISO period, not null580*/581@Override // override with covariant return type582public Period period(int years, int months, int days) {583return Period.of(years, months, days);584}585586//-----------------------------------------------------------------------587/**588* Writes the Chronology using a589* <a href="../../../serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.590* @serialData591* <pre>592* out.writeByte(1); // identifies a Chronology593* out.writeUTF(getId());594* </pre>595*596* @return the instance of {@code Ser}, not null597*/598@Override599Object writeReplace() {600return super.writeReplace();601}602603/**604* Defend against malicious streams.605*606* @param s the stream to read607* @throws InvalidObjectException always608*/609private void readObject(ObjectInputStream s) throws InvalidObjectException {610throw new InvalidObjectException("Deserialization via serialization delegate");611}612}613614615