Path: blob/master/src/java.base/share/classes/java/time/chrono/ThaiBuddhistDate.java
41159 views
/*1* Copyright (c) 2012, 2019, 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.ThaiBuddhistChronology.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 Thai Buddhist calendar system.88* <p>89* This date operates using the {@linkplain ThaiBuddhistChronology Thai Buddhist calendar}.90* This calendar system is primarily used in Thailand.91* Dates are aligned such that {@code 2484-01-01 (Buddhist)} is {@code 1941-01-01 (ISO)}.92* <p>93* This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>94* class; programmers should treat instances that are95* {@linkplain #equals(Object) equal} as interchangeable and should not96* use instances for synchronization, or unpredictable behavior may97* occur. For example, in a future release, synchronization may fail.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*/105@jdk.internal.ValueBased106public final class ThaiBuddhistDate107extends ChronoLocalDateImpl<ThaiBuddhistDate>108implements ChronoLocalDate, Serializable {109110/**111* Serialization version.112*/113@java.io.Serial114private static final long serialVersionUID = -8722293800195731463L;115116/**117* The underlying date.118*/119private final transient LocalDate isoDate;120121//-----------------------------------------------------------------------122/**123* Obtains the current {@code ThaiBuddhistDate} from the system clock in the default time-zone.124* <p>125* This will query the {@link Clock#systemDefaultZone() system clock} in the default126* time-zone to obtain the current date.127* <p>128* Using this method will prevent the ability to use an alternate clock for testing129* because the clock is hard-coded.130*131* @return the current date using the system clock and default time-zone, not null132*/133public static ThaiBuddhistDate now() {134return now(Clock.systemDefaultZone());135}136137/**138* Obtains the current {@code ThaiBuddhistDate} from the system clock in the specified time-zone.139* <p>140* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.141* Specifying the time-zone avoids dependence on the default time-zone.142* <p>143* Using this method will prevent the ability to use an alternate clock for testing144* because the clock is hard-coded.145*146* @param zone the zone ID to use, not null147* @return the current date using the system clock, not null148*/149public static ThaiBuddhistDate now(ZoneId zone) {150return now(Clock.system(zone));151}152153/**154* Obtains the current {@code ThaiBuddhistDate} from the specified clock.155* <p>156* This will query the specified clock to obtain the current date - today.157* Using this method allows the use of an alternate clock for testing.158* The alternate clock may be introduced using {@linkplain Clock dependency injection}.159*160* @param clock the clock to use, not null161* @return the current date, not null162* @throws DateTimeException if the current date cannot be obtained163*/164public static ThaiBuddhistDate now(Clock clock) {165return new ThaiBuddhistDate(LocalDate.now(clock));166}167168/**169* Obtains a {@code ThaiBuddhistDate} representing a date in the Thai Buddhist calendar170* system from the proleptic-year, month-of-year and day-of-month fields.171* <p>172* This returns a {@code ThaiBuddhistDate} with the specified fields.173* The day must be valid for the year and month, otherwise an exception will be thrown.174*175* @param prolepticYear the Thai Buddhist proleptic-year176* @param month the Thai Buddhist month-of-year, from 1 to 12177* @param dayOfMonth the Thai Buddhist day-of-month, from 1 to 31178* @return the date in Thai Buddhist calendar system, not null179* @throws DateTimeException if the value of any field is out of range,180* or if the day-of-month is invalid for the month-year181*/182public static ThaiBuddhistDate of(int prolepticYear, int month, int dayOfMonth) {183return new ThaiBuddhistDate(LocalDate.of(prolepticYear - YEARS_DIFFERENCE, month, dayOfMonth));184}185186/**187* Obtains a {@code ThaiBuddhistDate} from a temporal object.188* <p>189* This obtains a date in the Thai Buddhist calendar system based on the specified temporal.190* A {@code TemporalAccessor} represents an arbitrary set of date and time information,191* which this factory converts to an instance of {@code ThaiBuddhistDate}.192* <p>193* The conversion typically uses the {@link ChronoField#EPOCH_DAY EPOCH_DAY}194* field, which is standardized across calendar systems.195* <p>196* This method matches the signature of the functional interface {@link TemporalQuery}197* allowing it to be used as a query via method reference, {@code ThaiBuddhistDate::from}.198*199* @param temporal the temporal object to convert, not null200* @return the date in Thai Buddhist calendar system, not null201* @throws DateTimeException if unable to convert to a {@code ThaiBuddhistDate}202*/203public static ThaiBuddhistDate from(TemporalAccessor temporal) {204return ThaiBuddhistChronology.INSTANCE.date(temporal);205}206207//-----------------------------------------------------------------------208/**209* Creates an instance from an ISO date.210*211* @param isoDate the standard local date, validated not null212*/213ThaiBuddhistDate(LocalDate isoDate) {214Objects.requireNonNull(isoDate, "isoDate");215this.isoDate = isoDate;216}217218//-----------------------------------------------------------------------219/**220* Gets the chronology of this date, which is the Thai Buddhist calendar system.221* <p>222* The {@code Chronology} represents the calendar system in use.223* The era and other fields in {@link ChronoField} are defined by the chronology.224*225* @return the Thai Buddhist chronology, not null226*/227@Override228public ThaiBuddhistChronology getChronology() {229return ThaiBuddhistChronology.INSTANCE;230}231232/**233* Gets the era applicable at this date.234* <p>235* The Thai Buddhist calendar system has two eras, 'BE' and 'BEFORE_BE',236* defined by {@link ThaiBuddhistEra}.237*238* @return the era applicable at this date, not null239*/240@Override241public ThaiBuddhistEra getEra() {242return (getProlepticYear() >= 1 ? ThaiBuddhistEra.BE : ThaiBuddhistEra.BEFORE_BE);243}244245/**246* Returns the length of the month represented by this date.247* <p>248* This returns the length of the month in days.249* Month lengths match those of the ISO calendar system.250*251* @return the length of the month in days252*/253@Override254public int lengthOfMonth() {255return isoDate.lengthOfMonth();256}257258//-----------------------------------------------------------------------259@Override260public ValueRange range(TemporalField field) {261if (field instanceof ChronoField) {262if (isSupported(field)) {263ChronoField f = (ChronoField) field;264switch (f) {265case DAY_OF_MONTH:266case DAY_OF_YEAR:267case ALIGNED_WEEK_OF_MONTH:268return isoDate.range(field);269case YEAR_OF_ERA: {270ValueRange range = YEAR.range();271long max = (getProlepticYear() <= 0 ? -(range.getMinimum() + YEARS_DIFFERENCE) + 1 : range.getMaximum() + YEARS_DIFFERENCE);272return ValueRange.of(1, max);273}274}275return getChronology().range(f);276}277throw new UnsupportedTemporalTypeException("Unsupported field: " + field);278}279return field.rangeRefinedBy(this);280}281282@Override283public long getLong(TemporalField field) {284if (field instanceof ChronoField) {285switch ((ChronoField) field) {286case PROLEPTIC_MONTH:287return getProlepticMonth();288case YEAR_OF_ERA: {289int prolepticYear = getProlepticYear();290return (prolepticYear >= 1 ? prolepticYear : 1 - prolepticYear);291}292case YEAR:293return getProlepticYear();294case ERA:295return (getProlepticYear() >= 1 ? 1 : 0);296}297return isoDate.getLong(field);298}299return field.getFrom(this);300}301302private long getProlepticMonth() {303return getProlepticYear() * 12L + isoDate.getMonthValue() - 1;304}305306private int getProlepticYear() {307return isoDate.getYear() + YEARS_DIFFERENCE;308}309310//-----------------------------------------------------------------------311@Override312public ThaiBuddhistDate with(TemporalField field, long newValue) {313if (field instanceof ChronoField chronoField) {314if (getLong(chronoField) == newValue) {315return this;316}317switch (chronoField) {318case PROLEPTIC_MONTH:319getChronology().range(chronoField).checkValidValue(newValue, chronoField);320return plusMonths(newValue - getProlepticMonth());321case YEAR_OF_ERA:322case YEAR:323case ERA: {324int nvalue = getChronology().range(chronoField).checkValidIntValue(newValue, chronoField);325switch (chronoField) {326case YEAR_OF_ERA:327return with(isoDate.withYear((getProlepticYear() >= 1 ? nvalue : 1 - nvalue) - YEARS_DIFFERENCE));328case YEAR:329return with(isoDate.withYear(nvalue - YEARS_DIFFERENCE));330case ERA:331return with(isoDate.withYear((1 - getProlepticYear()) - YEARS_DIFFERENCE));332}333}334}335return with(isoDate.with(field, newValue));336}337return super.with(field, newValue);338}339340/**341* {@inheritDoc}342* @throws DateTimeException {@inheritDoc}343* @throws ArithmeticException {@inheritDoc}344*/345@Override346public ThaiBuddhistDate with(TemporalAdjuster adjuster) {347return super.with(adjuster);348}349350/**351* {@inheritDoc}352* @throws DateTimeException {@inheritDoc}353* @throws ArithmeticException {@inheritDoc}354*/355@Override356public ThaiBuddhistDate plus(TemporalAmount amount) {357return super.plus(amount);358}359360/**361* {@inheritDoc}362* @throws DateTimeException {@inheritDoc}363* @throws ArithmeticException {@inheritDoc}364*/365@Override366public ThaiBuddhistDate minus(TemporalAmount amount) {367return super.minus(amount);368}369370//-----------------------------------------------------------------------371@Override372ThaiBuddhistDate plusYears(long years) {373return with(isoDate.plusYears(years));374}375376@Override377ThaiBuddhistDate plusMonths(long months) {378return with(isoDate.plusMonths(months));379}380381@Override382ThaiBuddhistDate plusWeeks(long weeksToAdd) {383return super.plusWeeks(weeksToAdd);384}385386@Override387ThaiBuddhistDate plusDays(long days) {388return with(isoDate.plusDays(days));389}390391@Override392public ThaiBuddhistDate plus(long amountToAdd, TemporalUnit unit) {393return super.plus(amountToAdd, unit);394}395396@Override397public ThaiBuddhistDate minus(long amountToAdd, TemporalUnit unit) {398return super.minus(amountToAdd, unit);399}400401@Override402ThaiBuddhistDate minusYears(long yearsToSubtract) {403return super.minusYears(yearsToSubtract);404}405406@Override407ThaiBuddhistDate minusMonths(long monthsToSubtract) {408return super.minusMonths(monthsToSubtract);409}410411@Override412ThaiBuddhistDate minusWeeks(long weeksToSubtract) {413return super.minusWeeks(weeksToSubtract);414}415416@Override417ThaiBuddhistDate minusDays(long daysToSubtract) {418return super.minusDays(daysToSubtract);419}420421private ThaiBuddhistDate with(LocalDate newDate) {422return (newDate.equals(isoDate) ? this : new ThaiBuddhistDate(newDate));423}424425@Override // for javadoc and covariant return type426@SuppressWarnings("unchecked")427public final ChronoLocalDateTime<ThaiBuddhistDate> atTime(LocalTime localTime) {428return (ChronoLocalDateTime<ThaiBuddhistDate>) super.atTime(localTime);429}430431@Override432public ChronoPeriod until(ChronoLocalDate endDate) {433Period period = isoDate.until(endDate);434return getChronology().period(period.getYears(), period.getMonths(), period.getDays());435}436437@Override // override for performance438public long toEpochDay() {439return isoDate.toEpochDay();440}441442//-------------------------------------------------------------------------443/**444* Compares this date to another date, including the chronology.445* <p>446* Compares this {@code ThaiBuddhistDate} with another ensuring that the date is the same.447* <p>448* Only objects of type {@code ThaiBuddhistDate} are compared, other types return false.449* To compare the dates of two {@code TemporalAccessor} instances, including dates450* in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.451*452* @param obj the object to check, null returns false453* @return true if this is equal to the other date454*/455@Override // override for performance456public boolean equals(Object obj) {457if (this == obj) {458return true;459}460return (obj instanceof ThaiBuddhistDate otherDate)461&& this.isoDate.equals(otherDate.isoDate);462}463464/**465* A hash code for this date.466*467* @return a suitable hash code based only on the Chronology and the date468*/469@Override // override for performance470public int hashCode() {471return getChronology().getId().hashCode() ^ isoDate.hashCode();472}473474//-----------------------------------------------------------------------475/**476* Defend against malicious streams.477*478* @param s the stream to read479* @throws InvalidObjectException always480*/481@java.io.Serial482private void readObject(ObjectInputStream s) throws InvalidObjectException {483throw new InvalidObjectException("Deserialization via serialization delegate");484}485486/**487* Writes the object using a488* <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.489* @serialData490* <pre>491* out.writeByte(10); // identifies a ThaiBuddhistDate492* out.writeInt(get(YEAR));493* out.writeByte(get(MONTH_OF_YEAR));494* out.writeByte(get(DAY_OF_MONTH));495* </pre>496*497* @return the instance of {@code Ser}, not null498*/499@java.io.Serial500private Object writeReplace() {501return new Ser(Ser.THAIBUDDHIST_DATE_TYPE, this);502}503504void writeExternal(DataOutput out) throws IOException {505// ThaiBuddhistChronology is implicit in the THAIBUDDHIST_DATE_TYPE506out.writeInt(this.get(YEAR));507out.writeByte(this.get(MONTH_OF_YEAR));508out.writeByte(this.get(DAY_OF_MONTH));509}510511static ThaiBuddhistDate readExternal(DataInput in) throws IOException {512int year = in.readInt();513int month = in.readByte();514int dayOfMonth = in.readByte();515return ThaiBuddhistChronology.INSTANCE.date(year, month, dayOfMonth);516}517518}519520521