Path: blob/master/src/java.base/share/classes/java/time/chrono/ChronoLocalDateImpl.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.temporal.ChronoField.DAY_OF_MONTH;59import static java.time.temporal.ChronoField.ERA;60import static java.time.temporal.ChronoField.MONTH_OF_YEAR;61import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;62import static java.time.temporal.ChronoField.YEAR_OF_ERA;6364import java.io.Serializable;65import java.time.DateTimeException;66import java.time.temporal.ChronoUnit;67import java.time.temporal.Temporal;68import java.time.temporal.TemporalAdjuster;69import java.time.temporal.TemporalAmount;70import java.time.temporal.TemporalField;71import java.time.temporal.TemporalUnit;72import java.time.temporal.UnsupportedTemporalTypeException;73import java.time.temporal.ValueRange;74import java.util.Objects;7576/**77* A date expressed in terms of a standard year-month-day calendar system.78* <p>79* This class is used by applications seeking to handle dates in non-ISO calendar systems.80* For example, the Japanese, Minguo, Thai Buddhist and others.81* <p>82* {@code ChronoLocalDate} is built on the generic concepts of year, month and day.83* The calendar system, represented by a {@link java.time.chrono.Chronology}, expresses the relationship between84* the fields and this class allows the resulting date to be manipulated.85* <p>86* Note that not all calendar systems are suitable for use with this class.87* For example, the Mayan calendar uses a system that bears no relation to years, months and days.88* <p>89* The API design encourages the use of {@code LocalDate} for the majority of the application.90* This includes code to read and write from a persistent data store, such as a database,91* and to send dates and times across a network. The {@code ChronoLocalDate} instance is then used92* at the user interface level to deal with localized input/output.93*94* <P>Example: </p>95* <pre>96* System.out.printf("Example()%n");97* // Enumerate the list of available calendars and print today for each98* Set<Chronology> chronos = Chronology.getAvailableChronologies();99* for (Chronology chrono : chronos) {100* ChronoLocalDate date = chrono.dateNow();101* System.out.printf(" %20s: %s%n", chrono.getID(), date.toString());102* }103*104* // Print the Hijrah date and calendar105* ChronoLocalDate date = Chronology.of("Hijrah").dateNow();106* int day = date.get(ChronoField.DAY_OF_MONTH);107* int dow = date.get(ChronoField.DAY_OF_WEEK);108* int month = date.get(ChronoField.MONTH_OF_YEAR);109* int year = date.get(ChronoField.YEAR);110* System.out.printf(" Today is %s %s %d-%s-%d%n", date.getChronology().getID(),111* dow, day, month, year);112*113* // Print today's date and the last day of the year114* ChronoLocalDate now1 = Chronology.of("Hijrah").dateNow();115* ChronoLocalDate first = now1.with(ChronoField.DAY_OF_MONTH, 1)116* .with(ChronoField.MONTH_OF_YEAR, 1);117* ChronoLocalDate last = first.plus(1, ChronoUnit.YEARS)118* .minus(1, ChronoUnit.DAYS);119* System.out.printf(" Today is %s: start: %s; end: %s%n", last.getChronology().getID(),120* first, last);121* </pre>122*123* <h2>Adding Calendars</h2>124* <p> The set of calendars is extensible by defining a subclass of {@link ChronoLocalDate}125* to represent a date instance and an implementation of {@code Chronology}126* to be the factory for the ChronoLocalDate subclass.127* </p>128* <p> To permit the discovery of the additional calendar types the implementation of129* {@code Chronology} must be registered as a Service implementing the {@code Chronology} interface130* in the {@code META-INF/Services} file as per the specification of {@link java.util.ServiceLoader}.131* The subclass must function according to the {@code Chronology} class description and must provide its132* {@link java.time.chrono.Chronology#getId() chronlogy ID} and {@link Chronology#getCalendarType() calendar type}. </p>133*134* @implSpec135* This abstract class must be implemented with care to ensure other classes operate correctly.136* All implementations that can be instantiated must be final, immutable and thread-safe.137* Subclasses should be Serializable wherever possible.138*139* @param <D> the ChronoLocalDate of this date-time140* @since 1.8141*/142abstract class ChronoLocalDateImpl<D extends ChronoLocalDate>143implements ChronoLocalDate, Temporal, TemporalAdjuster, Serializable {144145/**146* Serialization version.147*/148@java.io.Serial149private static final long serialVersionUID = 6282433883239719096L;150151/**152* Casts the {@code Temporal} to {@code ChronoLocalDate} ensuring it bas the specified chronology.153*154* @param chrono the chronology to check for, not null155* @param temporal a date-time to cast, not null156* @return the date-time checked and cast to {@code ChronoLocalDate}, not null157* @throws ClassCastException if the date-time cannot be cast to ChronoLocalDate158* or the chronology is not equal this Chronology159*/160static <D extends ChronoLocalDate> D ensureValid(Chronology chrono, Temporal temporal) {161@SuppressWarnings("unchecked")162D other = (D) temporal;163if (chrono.equals(other.getChronology()) == false) {164throw new ClassCastException("Chronology mismatch, expected: " + chrono.getId() + ", actual: " + other.getChronology().getId());165}166return other;167}168169//-----------------------------------------------------------------------170/**171* Creates an instance.172*/173ChronoLocalDateImpl() {174}175176@Override177@SuppressWarnings("unchecked")178public D with(TemporalAdjuster adjuster) {179return (D) ChronoLocalDate.super.with(adjuster);180}181182@Override183@SuppressWarnings("unchecked")184public D with(TemporalField field, long value) {185return (D) ChronoLocalDate.super.with(field, value);186}187188//-----------------------------------------------------------------------189@Override190@SuppressWarnings("unchecked")191public D plus(TemporalAmount amount) {192return (D) ChronoLocalDate.super.plus(amount);193}194195//-----------------------------------------------------------------------196@Override197@SuppressWarnings("unchecked")198public D plus(long amountToAdd, TemporalUnit unit) {199if (unit instanceof ChronoUnit chronoUnit) {200switch (chronoUnit) {201case DAYS: return plusDays(amountToAdd);202case WEEKS: return plusDays(Math.multiplyExact(amountToAdd, 7));203case MONTHS: return plusMonths(amountToAdd);204case YEARS: return plusYears(amountToAdd);205case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));206case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));207case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));208case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));209}210throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);211}212return (D) ChronoLocalDate.super.plus(amountToAdd, unit);213}214215@Override216@SuppressWarnings("unchecked")217public D minus(TemporalAmount amount) {218return (D) ChronoLocalDate.super.minus(amount);219}220221@Override222@SuppressWarnings("unchecked")223public D minus(long amountToSubtract, TemporalUnit unit) {224return (D) ChronoLocalDate.super.minus(amountToSubtract, unit);225}226227//-----------------------------------------------------------------------228/**229* Returns a copy of this date with the specified number of years added.230* <p>231* This adds the specified period in years to the date.232* In some cases, adding years can cause the resulting date to become invalid.233* If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure234* that the result is valid. Typically this will select the last valid day of the month.235* <p>236* This instance is immutable and unaffected by this method call.237*238* @param yearsToAdd the years to add, may be negative239* @return a date based on this one with the years added, not null240* @throws DateTimeException if the result exceeds the supported date range241*/242abstract D plusYears(long yearsToAdd);243244/**245* Returns a copy of this date with the specified number of months added.246* <p>247* This adds the specified period in months to the date.248* In some cases, adding months can cause the resulting date to become invalid.249* If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure250* that the result is valid. Typically this will select the last valid day of the month.251* <p>252* This instance is immutable and unaffected by this method call.253*254* @param monthsToAdd the months to add, may be negative255* @return a date based on this one with the months added, not null256* @throws DateTimeException if the result exceeds the supported date range257*/258abstract D plusMonths(long monthsToAdd);259260/**261* Returns a copy of this date with the specified number of weeks added.262* <p>263* This adds the specified period in weeks to the date.264* In some cases, adding weeks can cause the resulting date to become invalid.265* If this occurs, then other fields will be adjusted to ensure that the result is valid.266* <p>267* The default implementation uses {@link #plusDays(long)} using a 7 day week.268* <p>269* This instance is immutable and unaffected by this method call.270*271* @param weeksToAdd the weeks to add, may be negative272* @return a date based on this one with the weeks added, not null273* @throws DateTimeException if the result exceeds the supported date range274*/275D plusWeeks(long weeksToAdd) {276return plusDays(Math.multiplyExact(weeksToAdd, 7));277}278279/**280* Returns a copy of this date with the specified number of days added.281* <p>282* This adds the specified period in days to the date.283* <p>284* This instance is immutable and unaffected by this method call.285*286* @param daysToAdd the days to add, may be negative287* @return a date based on this one with the days added, not null288* @throws DateTimeException if the result exceeds the supported date range289*/290abstract D plusDays(long daysToAdd);291292//-----------------------------------------------------------------------293/**294* Returns a copy of this date with the specified number of years subtracted.295* <p>296* This subtracts the specified period in years to the date.297* In some cases, subtracting years can cause the resulting date to become invalid.298* If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure299* that the result is valid. Typically this will select the last valid day of the month.300* <p>301* The default implementation uses {@link #plusYears(long)}.302* <p>303* This instance is immutable and unaffected by this method call.304*305* @param yearsToSubtract the years to subtract, may be negative306* @return a date based on this one with the years subtracted, not null307* @throws DateTimeException if the result exceeds the supported date range308*/309@SuppressWarnings("unchecked")310D minusYears(long yearsToSubtract) {311return (yearsToSubtract == Long.MIN_VALUE ? ((ChronoLocalDateImpl<D>)plusYears(Long.MAX_VALUE)).plusYears(1) : plusYears(-yearsToSubtract));312}313314/**315* Returns a copy of this date with the specified number of months subtracted.316* <p>317* This subtracts the specified period in months to the date.318* In some cases, subtracting months can cause the resulting date to become invalid.319* If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure320* that the result is valid. Typically this will select the last valid day of the month.321* <p>322* The default implementation uses {@link #plusMonths(long)}.323* <p>324* This instance is immutable and unaffected by this method call.325*326* @param monthsToSubtract the months to subtract, may be negative327* @return a date based on this one with the months subtracted, not null328* @throws DateTimeException if the result exceeds the supported date range329*/330@SuppressWarnings("unchecked")331D minusMonths(long monthsToSubtract) {332return (monthsToSubtract == Long.MIN_VALUE ? ((ChronoLocalDateImpl<D>)plusMonths(Long.MAX_VALUE)).plusMonths(1) : plusMonths(-monthsToSubtract));333}334335/**336* Returns a copy of this date with the specified number of weeks subtracted.337* <p>338* This subtracts the specified period in weeks to the date.339* In some cases, subtracting weeks can cause the resulting date to become invalid.340* If this occurs, then other fields will be adjusted to ensure that the result is valid.341* <p>342* The default implementation uses {@link #plusWeeks(long)}.343* <p>344* This instance is immutable and unaffected by this method call.345*346* @param weeksToSubtract the weeks to subtract, may be negative347* @return a date based on this one with the weeks subtracted, not null348* @throws DateTimeException if the result exceeds the supported date range349*/350@SuppressWarnings("unchecked")351D minusWeeks(long weeksToSubtract) {352return (weeksToSubtract == Long.MIN_VALUE ? ((ChronoLocalDateImpl<D>)plusWeeks(Long.MAX_VALUE)).plusWeeks(1) : plusWeeks(-weeksToSubtract));353}354355/**356* Returns a copy of this date with the specified number of days subtracted.357* <p>358* This subtracts the specified period in days to the date.359* <p>360* The default implementation uses {@link #plusDays(long)}.361* <p>362* This instance is immutable and unaffected by this method call.363*364* @param daysToSubtract the days to subtract, may be negative365* @return a date based on this one with the days subtracted, not null366* @throws DateTimeException if the result exceeds the supported date range367*/368@SuppressWarnings("unchecked")369D minusDays(long daysToSubtract) {370return (daysToSubtract == Long.MIN_VALUE ? ((ChronoLocalDateImpl<D>)plusDays(Long.MAX_VALUE)).plusDays(1) : plusDays(-daysToSubtract));371}372373//-----------------------------------------------------------------------374@Override375public long until(Temporal endExclusive, TemporalUnit unit) {376Objects.requireNonNull(endExclusive, "endExclusive");377ChronoLocalDate end = getChronology().date(endExclusive);378if (unit instanceof ChronoUnit chronoUnit) {379switch (chronoUnit) {380case DAYS: return daysUntil(end);381case WEEKS: return daysUntil(end) / 7;382case MONTHS: return monthsUntil(end);383case YEARS: return monthsUntil(end) / 12;384case DECADES: return monthsUntil(end) / 120;385case CENTURIES: return monthsUntil(end) / 1200;386case MILLENNIA: return monthsUntil(end) / 12000;387case ERAS: return end.getLong(ERA) - getLong(ERA);388}389throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);390}391Objects.requireNonNull(unit, "unit");392return unit.between(this, end);393}394395private long daysUntil(ChronoLocalDate end) {396return end.toEpochDay() - toEpochDay(); // no overflow397}398399private long monthsUntil(ChronoLocalDate end) {400ValueRange range = getChronology().range(MONTH_OF_YEAR);401if (range.getMaximum() != 12) {402throw new IllegalStateException("ChronoLocalDateImpl only supports Chronologies with 12 months per year");403}404long packed1 = getLong(PROLEPTIC_MONTH) * 32L + get(DAY_OF_MONTH); // no overflow405long packed2 = end.getLong(PROLEPTIC_MONTH) * 32L + end.get(DAY_OF_MONTH); // no overflow406return (packed2 - packed1) / 32;407}408409@Override410public boolean equals(Object obj) {411if (this == obj) {412return true;413}414if (obj instanceof ChronoLocalDate) {415return compareTo((ChronoLocalDate) obj) == 0;416}417return false;418}419420@Override421public int hashCode() {422long epDay = toEpochDay();423return getChronology().hashCode() ^ ((int) (epDay ^ (epDay >>> 32)));424}425426@Override427public String toString() {428// getLong() reduces chances of exceptions in toString()429long yoe = getLong(YEAR_OF_ERA);430long moy = getLong(MONTH_OF_YEAR);431long dom = getLong(DAY_OF_MONTH);432StringBuilder buf = new StringBuilder(30);433buf.append(getChronology().toString())434.append(" ")435.append(getEra())436.append(" ")437.append(yoe)438.append(moy < 10 ? "-0" : "-").append(moy)439.append(dom < 10 ? "-0" : "-").append(dom);440return buf.toString();441}442443}444445446