Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/chrono/MinguoDate.java
38918 views
/*1* Copyright (c) 2012, 2013, 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* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos27*28* All rights reserved.29*30* Redistribution and use in source and binary forms, with or without31* modification, are permitted provided that the following conditions are met:32*33* * Redistributions of source code must retain the above copyright notice,34* this list of conditions and the following disclaimer.35*36* * Redistributions in binary form must reproduce the above copyright notice,37* this list of conditions and the following disclaimer in the documentation38* and/or other materials provided with the distribution.39*40* * Neither the name of JSR-310 nor the names of its contributors41* may be used to endorse or promote products derived from this software42* without specific prior written permission.43*44* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS45* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT46* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR47* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR48* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,49* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,50* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR51* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF52* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING53* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS54* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.55*/56package java.time.chrono;5758import static java.time.chrono.MinguoChronology.YEARS_DIFFERENCE;59import static java.time.temporal.ChronoField.DAY_OF_MONTH;60import static java.time.temporal.ChronoField.MONTH_OF_YEAR;61import static java.time.temporal.ChronoField.YEAR;6263import java.io.DataInput;64import java.io.DataOutput;65import java.io.IOException;66import java.io.InvalidObjectException;67import java.io.ObjectInputStream;68import java.io.Serializable;69import java.time.Clock;70import java.time.DateTimeException;71import java.time.LocalDate;72import java.time.LocalTime;73import java.time.Period;74import java.time.ZoneId;75import java.time.temporal.ChronoField;76import java.time.temporal.TemporalAccessor;77import java.time.temporal.TemporalAdjuster;78import java.time.temporal.TemporalAmount;79import java.time.temporal.TemporalField;80import java.time.temporal.TemporalQuery;81import java.time.temporal.TemporalUnit;82import java.time.temporal.UnsupportedTemporalTypeException;83import java.time.temporal.ValueRange;84import java.util.Objects;8586/**87* A date in the Minguo calendar system.88* <p>89* This date operates using the {@linkplain MinguoChronology Minguo calendar}.90* This calendar system is primarily used in the Republic of China, often known as Taiwan.91* Dates are aligned such that {@code 0001-01-01 (Minguo)} is {@code 1912-01-01 (ISO)}.92*93* <p>94* This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>95* class; use of identity-sensitive operations (including reference equality96* ({@code ==}), identity hash code, or synchronization) on instances of97* {@code MinguoDate} may have unpredictable results and should be avoided.98* The {@code equals} method should be used for comparisons.99*100* @implSpec101* This class is immutable and thread-safe.102*103* @since 1.8104*/105public final class MinguoDate106extends ChronoLocalDateImpl<MinguoDate>107implements ChronoLocalDate, Serializable {108109/**110* Serialization version.111*/112private static final long serialVersionUID = 1300372329181994526L;113114/**115* The underlying date.116*/117private final transient LocalDate isoDate;118119//-----------------------------------------------------------------------120/**121* Obtains the current {@code MinguoDate} from the system clock in the default time-zone.122* <p>123* This will query the {@link Clock#systemDefaultZone() system clock} in the default124* time-zone to obtain the current date.125* <p>126* Using this method will prevent the ability to use an alternate clock for testing127* because the clock is hard-coded.128*129* @return the current date using the system clock and default time-zone, not null130*/131public static MinguoDate now() {132return now(Clock.systemDefaultZone());133}134135/**136* Obtains the current {@code MinguoDate} from the system clock in the specified time-zone.137* <p>138* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.139* Specifying the time-zone avoids dependence on the default time-zone.140* <p>141* Using this method will prevent the ability to use an alternate clock for testing142* because the clock is hard-coded.143*144* @param zone the zone ID to use, not null145* @return the current date using the system clock, not null146*/147public static MinguoDate now(ZoneId zone) {148return now(Clock.system(zone));149}150151/**152* Obtains the current {@code MinguoDate} from the specified clock.153* <p>154* This will query the specified clock to obtain the current date - today.155* Using this method allows the use of an alternate clock for testing.156* The alternate clock may be introduced using {@linkplain Clock dependency injection}.157*158* @param clock the clock to use, not null159* @return the current date, not null160* @throws DateTimeException if the current date cannot be obtained161*/162public static MinguoDate now(Clock clock) {163return new MinguoDate(LocalDate.now(clock));164}165166/**167* Obtains a {@code MinguoDate} representing a date in the Minguo calendar168* system from the proleptic-year, month-of-year and day-of-month fields.169* <p>170* This returns a {@code MinguoDate} with the specified fields.171* The day must be valid for the year and month, otherwise an exception will be thrown.172*173* @param prolepticYear the Minguo proleptic-year174* @param month the Minguo month-of-year, from 1 to 12175* @param dayOfMonth the Minguo day-of-month, from 1 to 31176* @return the date in Minguo calendar system, not null177* @throws DateTimeException if the value of any field is out of range,178* or if the day-of-month is invalid for the month-year179*/180public static MinguoDate of(int prolepticYear, int month, int dayOfMonth) {181return new MinguoDate(LocalDate.of(prolepticYear + YEARS_DIFFERENCE, month, dayOfMonth));182}183184/**185* Obtains a {@code MinguoDate} from a temporal object.186* <p>187* This obtains a date in the Minguo calendar system based on the specified temporal.188* A {@code TemporalAccessor} represents an arbitrary set of date and time information,189* which this factory converts to an instance of {@code MinguoDate}.190* <p>191* The conversion typically uses the {@link ChronoField#EPOCH_DAY EPOCH_DAY}192* field, which is standardized across calendar systems.193* <p>194* This method matches the signature of the functional interface {@link TemporalQuery}195* allowing it to be used as a query via method reference, {@code MinguoDate::from}.196*197* @param temporal the temporal object to convert, not null198* @return the date in Minguo calendar system, not null199* @throws DateTimeException if unable to convert to a {@code MinguoDate}200*/201public static MinguoDate from(TemporalAccessor temporal) {202return MinguoChronology.INSTANCE.date(temporal);203}204205//-----------------------------------------------------------------------206/**207* Creates an instance from an ISO date.208*209* @param isoDate the standard local date, validated not null210*/211MinguoDate(LocalDate isoDate) {212Objects.requireNonNull(isoDate, "isoDate");213this.isoDate = isoDate;214}215216//-----------------------------------------------------------------------217/**218* Gets the chronology of this date, which is the Minguo calendar system.219* <p>220* The {@code Chronology} represents the calendar system in use.221* The era and other fields in {@link ChronoField} are defined by the chronology.222*223* @return the Minguo chronology, not null224*/225@Override226public MinguoChronology getChronology() {227return MinguoChronology.INSTANCE;228}229230/**231* Gets the era applicable at this date.232* <p>233* The Minguo calendar system has two eras, 'ROC' and 'BEFORE_ROC',234* defined by {@link MinguoEra}.235*236* @return the era applicable at this date, not null237*/238@Override239public MinguoEra getEra() {240return (getProlepticYear() >= 1 ? MinguoEra.ROC : MinguoEra.BEFORE_ROC);241}242243/**244* Returns the length of the month represented by this date.245* <p>246* This returns the length of the month in days.247* Month lengths match those of the ISO calendar system.248*249* @return the length of the month in days250*/251@Override252public int lengthOfMonth() {253return isoDate.lengthOfMonth();254}255256//-----------------------------------------------------------------------257@Override258public ValueRange range(TemporalField field) {259if (field instanceof ChronoField) {260if (isSupported(field)) {261ChronoField f = (ChronoField) field;262switch (f) {263case DAY_OF_MONTH:264case DAY_OF_YEAR:265case ALIGNED_WEEK_OF_MONTH:266return isoDate.range(field);267case YEAR_OF_ERA: {268ValueRange range = YEAR.range();269long max = (getProlepticYear() <= 0 ? -range.getMinimum() + 1 + YEARS_DIFFERENCE : range.getMaximum() - YEARS_DIFFERENCE);270return ValueRange.of(1, max);271}272}273return getChronology().range(f);274}275throw new UnsupportedTemporalTypeException("Unsupported field: " + field);276}277return field.rangeRefinedBy(this);278}279280@Override281public long getLong(TemporalField field) {282if (field instanceof ChronoField) {283switch ((ChronoField) field) {284case PROLEPTIC_MONTH:285return getProlepticMonth();286case YEAR_OF_ERA: {287int prolepticYear = getProlepticYear();288return (prolepticYear >= 1 ? prolepticYear : 1 - prolepticYear);289}290case YEAR:291return getProlepticYear();292case ERA:293return (getProlepticYear() >= 1 ? 1 : 0);294}295return isoDate.getLong(field);296}297return field.getFrom(this);298}299300private long getProlepticMonth() {301return getProlepticYear() * 12L + isoDate.getMonthValue() - 1;302}303304private int getProlepticYear() {305return isoDate.getYear() - YEARS_DIFFERENCE;306}307308//-----------------------------------------------------------------------309@Override310public MinguoDate with(TemporalField field, long newValue) {311if (field instanceof ChronoField) {312ChronoField f = (ChronoField) field;313if (getLong(f) == newValue) {314return this;315}316switch (f) {317case PROLEPTIC_MONTH:318getChronology().range(f).checkValidValue(newValue, f);319return plusMonths(newValue - getProlepticMonth());320case YEAR_OF_ERA:321case YEAR:322case ERA: {323int nvalue = getChronology().range(f).checkValidIntValue(newValue, f);324switch (f) {325case YEAR_OF_ERA:326return with(isoDate.withYear(getProlepticYear() >= 1 ? nvalue + YEARS_DIFFERENCE : (1 - nvalue) + YEARS_DIFFERENCE));327case YEAR:328return with(isoDate.withYear(nvalue + YEARS_DIFFERENCE));329case ERA:330return with(isoDate.withYear((1 - getProlepticYear()) + YEARS_DIFFERENCE));331}332}333}334return with(isoDate.with(field, newValue));335}336return super.with(field, newValue);337}338339/**340* {@inheritDoc}341* @throws DateTimeException {@inheritDoc}342* @throws ArithmeticException {@inheritDoc}343*/344@Override345public MinguoDate with(TemporalAdjuster adjuster) {346return super.with(adjuster);347}348349/**350* {@inheritDoc}351* @throws DateTimeException {@inheritDoc}352* @throws ArithmeticException {@inheritDoc}353*/354@Override355public MinguoDate plus(TemporalAmount amount) {356return super.plus(amount);357}358359/**360* {@inheritDoc}361* @throws DateTimeException {@inheritDoc}362* @throws ArithmeticException {@inheritDoc}363*/364@Override365public MinguoDate minus(TemporalAmount amount) {366return super.minus(amount);367}368369//-----------------------------------------------------------------------370@Override371MinguoDate plusYears(long years) {372return with(isoDate.plusYears(years));373}374375@Override376MinguoDate plusMonths(long months) {377return with(isoDate.plusMonths(months));378}379380@Override381MinguoDate plusWeeks(long weeksToAdd) {382return super.plusWeeks(weeksToAdd);383}384385@Override386MinguoDate plusDays(long days) {387return with(isoDate.plusDays(days));388}389390@Override391public MinguoDate plus(long amountToAdd, TemporalUnit unit) {392return super.plus(amountToAdd, unit);393}394395@Override396public MinguoDate minus(long amountToAdd, TemporalUnit unit) {397return super.minus(amountToAdd, unit);398}399400@Override401MinguoDate minusYears(long yearsToSubtract) {402return super.minusYears(yearsToSubtract);403}404405@Override406MinguoDate minusMonths(long monthsToSubtract) {407return super.minusMonths(monthsToSubtract);408}409410@Override411MinguoDate minusWeeks(long weeksToSubtract) {412return super.minusWeeks(weeksToSubtract);413}414415@Override416MinguoDate minusDays(long daysToSubtract) {417return super.minusDays(daysToSubtract);418}419420private MinguoDate with(LocalDate newDate) {421return (newDate.equals(isoDate) ? this : new MinguoDate(newDate));422}423424@Override // for javadoc and covariant return type425@SuppressWarnings("unchecked")426public final ChronoLocalDateTime<MinguoDate> atTime(LocalTime localTime) {427return (ChronoLocalDateTime<MinguoDate>)super.atTime(localTime);428}429430@Override431public ChronoPeriod until(ChronoLocalDate endDate) {432Period period = isoDate.until(endDate);433return getChronology().period(period.getYears(), period.getMonths(), period.getDays());434}435436@Override // override for performance437public long toEpochDay() {438return isoDate.toEpochDay();439}440441//-------------------------------------------------------------------------442/**443* Compares this date to another date, including the chronology.444* <p>445* Compares this {@code MinguoDate} with another ensuring that the date is the same.446* <p>447* Only objects of type {@code MinguoDate} are compared, other types return false.448* To compare the dates of two {@code TemporalAccessor} instances, including dates449* in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.450*451* @param obj the object to check, null returns false452* @return true if this is equal to the other date453*/454@Override // override for performance455public boolean equals(Object obj) {456if (this == obj) {457return true;458}459if (obj instanceof MinguoDate) {460MinguoDate otherDate = (MinguoDate) obj;461return this.isoDate.equals(otherDate.isoDate);462}463return false;464}465466/**467* A hash code for this date.468*469* @return a suitable hash code based only on the Chronology and the date470*/471@Override // override for performance472public int hashCode() {473return getChronology().getId().hashCode() ^ isoDate.hashCode();474}475476//-----------------------------------------------------------------------477/**478* Defend against malicious streams.479*480* @param s the stream to read481* @throws InvalidObjectException always482*/483private void readObject(ObjectInputStream s) throws InvalidObjectException {484throw new InvalidObjectException("Deserialization via serialization delegate");485}486487/**488* Writes the object using a489* <a href="../../../serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.490* @serialData491* <pre>492* out.writeByte(8); // identifies a MinguoDate493* out.writeInt(get(YEAR));494* out.writeByte(get(MONTH_OF_YEAR));495* out.writeByte(get(DAY_OF_MONTH));496* </pre>497*498* @return the instance of {@code Ser}, not null499*/500private Object writeReplace() {501return new Ser(Ser.MINGUO_DATE_TYPE, this);502}503504void writeExternal(DataOutput out) throws IOException {505// MinguoChronology is implicit in the MINGUO_DATE_TYPE506out.writeInt(get(YEAR));507out.writeByte(get(MONTH_OF_YEAR));508out.writeByte(get(DAY_OF_MONTH));509}510511static MinguoDate readExternal(DataInput in) throws IOException {512int year = in.readInt();513int month = in.readByte();514int dayOfMonth = in.readByte();515return MinguoChronology.INSTANCE.date(year, month, dayOfMonth);516}517518}519520521