1 /*
   2  * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
  28  *
  29  * All rights reserved.
  30  *
  31  * Redistribution and use in source and binary forms, with or without
  32  * modification, are permitted provided that the following conditions are met:
  33  *
  34  *  * Redistributions of source code must retain the above copyright notice,
  35  *    this list of conditions and the following disclaimer.
  36  *
  37  *  * Redistributions in binary form must reproduce the above copyright notice,
  38  *    this list of conditions and the following disclaimer in the documentation
  39  *    and/or other materials provided with the distribution.
  40  *
  41  *  * Neither the name of JSR-310 nor the names of its contributors
  42  *    may be used to endorse or promote products derived from this software
  43  *    without specific prior written permission.
  44  *
  45  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  46  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  47  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  48  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  49  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  50  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  51  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  52  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  53  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  54  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  55  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  56  */
  57 package java.time.chrono;
  58 
  59 import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;
  60 import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;
  61 import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;
  62 import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;
  63 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
  64 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  65 import static java.time.temporal.ChronoField.YEAR;
  66 
  67 import java.io.IOException;
  68 import java.io.InvalidObjectException;
  69 import java.io.ObjectInput;
  70 import java.io.ObjectInputStream;
  71 import java.io.ObjectOutput;
  72 import java.io.Serializable;
  73 import java.time.Clock;
  74 import java.time.DateTimeException;
  75 import java.time.LocalDate;
  76 import java.time.LocalTime;
  77 import java.time.ZoneId;
  78 import java.time.temporal.ChronoField;
  79 import java.time.temporal.TemporalAccessor;
  80 import java.time.temporal.TemporalAdjuster;
  81 import java.time.temporal.TemporalAmount;
  82 import java.time.temporal.TemporalField;
  83 import java.time.temporal.TemporalQuery;
  84 import java.time.temporal.TemporalUnit;
  85 import java.time.temporal.UnsupportedTemporalTypeException;
  86 import java.time.temporal.ValueRange;
  87 
  88 /**
  89  * A date in the Hijrah calendar system.
  90  * <p>
  91  * This date operates using one of several variants of the
  92  * {@linkplain HijrahChronology Hijrah calendar}.
  93  * <p>
  94  * The Hijrah calendar has a different total of days in a year than
  95  * Gregorian calendar, and the length of each month is based on the period
  96  * of a complete revolution of the moon around the earth
  97  * (as between successive new moons).
  98  * Refer to the {@link HijrahChronology} for details of supported variants.
  99  * <p>
 100  * Each HijrahDate is created bound to a particular HijrahChronology,
 101  * The same chronology is propagated to each HijrahDate computed from the date.
 102  * To use a different Hijrah variant, its HijrahChronology can be used
 103  * to create new HijrahDate instances.
 104  * Alternatively, the {@link #withVariant} method can be used to convert
 105  * to a new HijrahChronology.
 106  *
 107  * <p>
 108  * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
 109  * class; use of identity-sensitive operations (including reference equality
 110  * ({@code ==}), identity hash code, or synchronization) on instances of
 111  * {@code HijrahDate} may have unpredictable results and should be avoided.
 112  * The {@code equals} method should be used for comparisons.
 113  *
 114  * @implSpec
 115  * This class is immutable and thread-safe.
 116  *
 117  * @since 1.8
 118  */
 119 public final class HijrahDate
 120         extends ChronoLocalDateImpl<HijrahDate>
 121         implements ChronoLocalDate, Serializable {
 122 
 123     /**
 124      * Serialization version.
 125      */
 126     @java.io.Serial
 127     private static final long serialVersionUID = -5207853542612002020L;
 128     /**
 129      * The Chronology of this HijrahDate.
 130      */
 131     private final transient HijrahChronology chrono;
 132     /**
 133      * The proleptic year.
 134      */
 135     private final transient int prolepticYear;
 136     /**
 137      * The month-of-year.
 138      */
 139     private final transient int monthOfYear;
 140     /**
 141      * The day-of-month.
 142      */
 143     private final transient int dayOfMonth;
 144 
 145     //-------------------------------------------------------------------------
 146     /**
 147      * Obtains an instance of {@code HijrahDate} from the Hijrah proleptic year,
 148      * month-of-year and day-of-month.
 149      *
 150      * @param prolepticYear  the proleptic year to represent in the Hijrah calendar
 151      * @param monthOfYear  the month-of-year to represent, from 1 to 12
 152      * @param dayOfMonth  the day-of-month to represent, from 1 to 30
 153      * @return the Hijrah date, never null
 154      * @throws DateTimeException if the value of any field is out of range
 155      */
 156     static HijrahDate of(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
 157         return new HijrahDate(chrono, prolepticYear, monthOfYear, dayOfMonth);
 158     }
 159 
 160     /**
 161      * Returns a HijrahDate for the chronology and epochDay.
 162      * @param chrono The Hijrah chronology
 163      * @param epochDay the epoch day
 164      * @return a HijrahDate for the epoch day; non-null
 165      */
 166     static HijrahDate ofEpochDay(HijrahChronology chrono, long epochDay) {
 167         return new HijrahDate(chrono, epochDay);
 168     }
 169 
 170     //-----------------------------------------------------------------------
 171     /**
 172      * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
 173      * in the default time-zone.
 174      * <p>
 175      * This will query the {@link Clock#systemDefaultZone() system clock} in the default
 176      * time-zone to obtain the current date.
 177      * <p>
 178      * Using this method will prevent the ability to use an alternate clock for testing
 179      * because the clock is hard-coded.
 180      *
 181      * @return the current date using the system clock and default time-zone, not null
 182      */
 183     public static HijrahDate now() {
 184         return now(Clock.systemDefaultZone());
 185     }
 186 
 187     /**
 188      * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
 189      * in the specified time-zone.
 190      * <p>
 191      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
 192      * Specifying the time-zone avoids dependence on the default time-zone.
 193      * <p>
 194      * Using this method will prevent the ability to use an alternate clock for testing
 195      * because the clock is hard-coded.
 196      *
 197      * @param zone  the zone ID to use, not null
 198      * @return the current date using the system clock, not null
 199      */
 200     public static HijrahDate now(ZoneId zone) {
 201         return now(Clock.system(zone));
 202     }
 203 
 204     /**
 205      * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
 206      * from the specified clock.
 207      * <p>
 208      * This will query the specified clock to obtain the current date - today.
 209      * Using this method allows the use of an alternate clock for testing.
 210      * The alternate clock may be introduced using {@linkplain Clock dependency injection}.
 211      *
 212      * @param clock  the clock to use, not null
 213      * @return the current date, not null
 214      * @throws DateTimeException if the current date cannot be obtained
 215      */
 216     public static HijrahDate now(Clock clock) {
 217         return HijrahDate.ofEpochDay(HijrahChronology.INSTANCE, LocalDate.now(clock).toEpochDay());
 218     }
 219 
 220     /**
 221      * Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar
 222      * from the proleptic-year, month-of-year and day-of-month fields.
 223      * <p>
 224      * This returns a {@code HijrahDate} with the specified fields.
 225      * The day must be valid for the year and month, otherwise an exception will be thrown.
 226      *
 227      * @param prolepticYear  the Hijrah proleptic-year
 228      * @param month  the Hijrah month-of-year, from 1 to 12
 229      * @param dayOfMonth  the Hijrah day-of-month, from 1 to 30
 230      * @return the date in Hijrah calendar system, not null
 231      * @throws DateTimeException if the value of any field is out of range,
 232      *  or if the day-of-month is invalid for the month-year
 233      */
 234     public static HijrahDate of(int prolepticYear, int month, int dayOfMonth) {
 235         return HijrahChronology.INSTANCE.date(prolepticYear, month, dayOfMonth);
 236     }
 237 
 238     /**
 239      * Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar from a temporal object.
 240      * <p>
 241      * This obtains a date in the Hijrah calendar system based on the specified temporal.
 242      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 243      * which this factory converts to an instance of {@code HijrahDate}.
 244      * <p>
 245      * The conversion typically uses the {@link ChronoField#EPOCH_DAY EPOCH_DAY}
 246      * field, which is standardized across calendar systems.
 247      * <p>
 248      * This method matches the signature of the functional interface {@link TemporalQuery}
 249      * allowing it to be used as a query via method reference, {@code HijrahDate::from}.
 250      *
 251      * @param temporal  the temporal object to convert, not null
 252      * @return the date in Hijrah calendar system, not null
 253      * @throws DateTimeException if unable to convert to a {@code HijrahDate}
 254      */
 255     public static HijrahDate from(TemporalAccessor temporal) {
 256         return HijrahChronology.INSTANCE.date(temporal);
 257     }
 258 
 259     //-----------------------------------------------------------------------
 260     /**
 261      * Constructs an {@code HijrahDate} with the proleptic-year, month-of-year and
 262      * day-of-month fields.
 263      *
 264      * @param chrono The chronology to create the date with
 265      * @param prolepticYear the proleptic year
 266      * @param monthOfYear the month of year
 267      * @param dayOfMonth the day of month
 268      */
 269     private HijrahDate(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
 270         // Computing the Gregorian day checks the valid ranges
 271         chrono.getEpochDay(prolepticYear, monthOfYear, dayOfMonth);
 272 
 273         this.chrono = chrono;
 274         this.prolepticYear = prolepticYear;
 275         this.monthOfYear = monthOfYear;
 276         this.dayOfMonth = dayOfMonth;
 277     }
 278 
 279     /**
 280      * Constructs an instance with the Epoch Day.
 281      *
 282      * @param epochDay  the epochDay
 283      */
 284     private HijrahDate(HijrahChronology chrono, long epochDay) {
 285         int[] dateInfo = chrono.getHijrahDateInfo((int)epochDay);
 286 
 287         this.chrono = chrono;
 288         this.prolepticYear = dateInfo[0];
 289         this.monthOfYear = dateInfo[1];
 290         this.dayOfMonth = dateInfo[2];
 291     }
 292 
 293     //-----------------------------------------------------------------------
 294     /**
 295      * Gets the chronology of this date, which is the Hijrah calendar system.
 296      * <p>
 297      * The {@code Chronology} represents the calendar system in use.
 298      * The era and other fields in {@link ChronoField} are defined by the chronology.
 299      *
 300      * @return the Hijrah chronology, not null
 301      */
 302     @Override
 303     public HijrahChronology getChronology() {
 304         return chrono;
 305     }
 306 
 307     /**
 308      * Gets the era applicable at this date.
 309      * <p>
 310      * The Hijrah calendar system has one era, 'AH',
 311      * defined by {@link HijrahEra}.
 312      *
 313      * @return the era applicable at this date, not null
 314      */
 315     @Override
 316     public HijrahEra getEra() {
 317         return HijrahEra.AH;
 318     }
 319 
 320     /**
 321      * Returns the length of the month represented by this date.
 322      * <p>
 323      * This returns the length of the month in days.
 324      * Month lengths in the Hijrah calendar system vary between 29 and 30 days.
 325      *
 326      * @return the length of the month in days
 327      */
 328     @Override
 329     public int lengthOfMonth() {
 330         return chrono.getMonthLength(prolepticYear, monthOfYear);
 331     }
 332 
 333     /**
 334      * Returns the length of the year represented by this date.
 335      * <p>
 336      * This returns the length of the year in days.
 337      * A Hijrah calendar system year is typically shorter than
 338      * that of the ISO calendar system.
 339      *
 340      * @return the length of the year in days
 341      */
 342     @Override
 343     public int lengthOfYear() {
 344         return chrono.getYearLength(prolepticYear);
 345     }
 346 
 347     //-----------------------------------------------------------------------
 348     @Override
 349     public ValueRange range(TemporalField field) {
 350         if (field instanceof ChronoField) {
 351             if (isSupported(field)) {
 352                 ChronoField f = (ChronoField) field;
 353                 switch (f) {
 354                     case DAY_OF_MONTH: return ValueRange.of(1, lengthOfMonth());
 355                     case DAY_OF_YEAR: return ValueRange.of(1, lengthOfYear());
 356                     case ALIGNED_WEEK_OF_MONTH: return ValueRange.of(1, 5);  // TODO
 357                     // TODO does the limited range of valid years cause years to
 358                     // start/end part way through? that would affect range
 359                 }
 360                 return getChronology().range(f);
 361             }
 362             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 363         }
 364         return field.rangeRefinedBy(this);
 365     }
 366 
 367     @Override
 368     public long getLong(TemporalField field) {
 369         if (field instanceof ChronoField) {
 370             switch ((ChronoField) field) {
 371                 case DAY_OF_WEEK: return getDayOfWeek();
 372                 case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((dayOfMonth - 1) % 7) + 1;
 373                 case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((getDayOfYear() - 1) % 7) + 1;
 374                 case DAY_OF_MONTH: return this.dayOfMonth;
 375                 case DAY_OF_YEAR: return this.getDayOfYear();
 376                 case EPOCH_DAY: return toEpochDay();
 377                 case ALIGNED_WEEK_OF_MONTH: return ((dayOfMonth - 1) / 7) + 1;
 378                 case ALIGNED_WEEK_OF_YEAR: return ((getDayOfYear() - 1) / 7) + 1;
 379                 case MONTH_OF_YEAR: return monthOfYear;
 380                 case PROLEPTIC_MONTH: return getProlepticMonth();
 381                 case YEAR_OF_ERA: return prolepticYear;
 382                 case YEAR: return prolepticYear;
 383                 case ERA: return getEraValue();
 384             }
 385             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 386         }
 387         return field.getFrom(this);
 388     }
 389 
 390     private long getProlepticMonth() {
 391         return prolepticYear * 12L + monthOfYear - 1;
 392     }
 393 
 394     @Override
 395     public HijrahDate with(TemporalField field, long newValue) {
 396         if (field instanceof ChronoField) {
 397             ChronoField f = (ChronoField) field;
 398             // not using checkValidIntValue so EPOCH_DAY and PROLEPTIC_MONTH work
 399             chrono.range(f).checkValidValue(newValue, f);    // TODO: validate value
 400             int nvalue = (int) newValue;
 401             switch (f) {
 402                 case DAY_OF_WEEK: return plusDays(newValue - getDayOfWeek());
 403                 case ALIGNED_DAY_OF_WEEK_IN_MONTH: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));
 404                 case ALIGNED_DAY_OF_WEEK_IN_YEAR: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));
 405                 case DAY_OF_MONTH: return resolvePreviousValid(prolepticYear, monthOfYear, nvalue);
 406                 case DAY_OF_YEAR: return plusDays(Math.min(nvalue, lengthOfYear()) - getDayOfYear());
 407                 case EPOCH_DAY: return new HijrahDate(chrono, newValue);
 408                 case ALIGNED_WEEK_OF_MONTH: return plusDays((newValue - getLong(ALIGNED_WEEK_OF_MONTH)) * 7);
 409                 case ALIGNED_WEEK_OF_YEAR: return plusDays((newValue - getLong(ALIGNED_WEEK_OF_YEAR)) * 7);
 410                 case MONTH_OF_YEAR: return resolvePreviousValid(prolepticYear, nvalue, dayOfMonth);
 411                 case PROLEPTIC_MONTH: return plusMonths(newValue - getProlepticMonth());
 412                 case YEAR_OF_ERA: return resolvePreviousValid(prolepticYear >= 1 ? nvalue : 1 - nvalue, monthOfYear, dayOfMonth);
 413                 case YEAR: return resolvePreviousValid(nvalue, monthOfYear, dayOfMonth);
 414                 case ERA: return resolvePreviousValid(1 - prolepticYear, monthOfYear, dayOfMonth);
 415             }
 416             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 417         }
 418         return super.with(field, newValue);
 419     }
 420 
 421     private HijrahDate resolvePreviousValid(int prolepticYear, int month, int day) {
 422         int monthDays = chrono.getMonthLength(prolepticYear, month);
 423         if (day > monthDays) {
 424             day = monthDays;
 425         }
 426         return HijrahDate.of(chrono, prolepticYear, month, day);
 427     }
 428 
 429     /**
 430      * {@inheritDoc}
 431      * @throws DateTimeException if unable to make the adjustment.
 432      *     For example, if the adjuster requires an ISO chronology
 433      * @throws ArithmeticException {@inheritDoc}
 434      */
 435     @Override
 436     public  HijrahDate with(TemporalAdjuster adjuster) {
 437         return super.with(adjuster);
 438     }
 439 
 440     /**
 441      * Returns a {@code HijrahDate} with the Chronology requested.
 442      * <p>
 443      * The year, month, and day are checked against the new requested
 444      * HijrahChronology.  If the chronology has a shorter month length
 445      * for the month, the day is reduced to be the last day of the month.
 446      *
 447      * @param chronology the new HijrahChonology, non-null
 448      * @return a HijrahDate with the requested HijrahChronology, non-null
 449      */
 450     public HijrahDate withVariant(HijrahChronology chronology) {
 451         if (chrono == chronology) {
 452             return this;
 453         }
 454         // Like resolvePreviousValid the day is constrained to stay in the same month
 455         int monthDays = chronology.getDayOfYear(prolepticYear, monthOfYear);
 456         return HijrahDate.of(chronology, prolepticYear, monthOfYear,(dayOfMonth > monthDays) ? monthDays : dayOfMonth );
 457     }
 458 
 459     /**
 460      * {@inheritDoc}
 461      * @throws DateTimeException {@inheritDoc}
 462      * @throws ArithmeticException {@inheritDoc}
 463      */
 464     @Override
 465     public HijrahDate plus(TemporalAmount amount) {
 466         return super.plus(amount);
 467     }
 468 
 469     /**
 470      * {@inheritDoc}
 471      * @throws DateTimeException {@inheritDoc}
 472      * @throws ArithmeticException {@inheritDoc}
 473      */
 474     @Override
 475     public HijrahDate minus(TemporalAmount amount) {
 476         return super.minus(amount);
 477     }
 478 
 479     @Override
 480     public long toEpochDay() {
 481         return chrono.getEpochDay(prolepticYear, monthOfYear, dayOfMonth);
 482     }
 483 
 484     /**
 485      * Gets the day-of-year field.
 486      * <p>
 487      * This method returns the primitive {@code int} value for the day-of-year.
 488      *
 489      * @return the day-of-year
 490      */
 491     private int getDayOfYear() {
 492         return chrono.getDayOfYear(prolepticYear, monthOfYear) + dayOfMonth;
 493     }
 494 
 495     /**
 496      * Gets the day-of-week value.
 497      *
 498      * @return the day-of-week; computed from the epochday
 499      */
 500     private int getDayOfWeek() {
 501         int dow0 = Math.floorMod(toEpochDay() + 3, 7);
 502         return dow0 + 1;
 503     }
 504 
 505     /**
 506      * Gets the Era of this date.
 507      *
 508      * @return the Era of this date; computed from epochDay
 509      */
 510     private int getEraValue() {
 511         return (prolepticYear > 1 ? 1 : 0);
 512     }
 513 
 514     //-----------------------------------------------------------------------
 515     /**
 516      * Checks if the year is a leap year, according to the Hijrah calendar system rules.
 517      *
 518      * @return true if this date is in a leap year
 519      */
 520     @Override
 521     public boolean isLeapYear() {
 522         return chrono.isLeapYear(prolepticYear);
 523     }
 524 
 525     //-----------------------------------------------------------------------
 526     @Override
 527     HijrahDate plusYears(long years) {
 528         if (years == 0) {
 529             return this;
 530         }
 531         int newYear = Math.addExact(this.prolepticYear, (int)years);
 532         return resolvePreviousValid(newYear, monthOfYear, dayOfMonth);
 533     }
 534 
 535     @Override
 536     HijrahDate plusMonths(long monthsToAdd) {
 537         if (monthsToAdd == 0) {
 538             return this;
 539         }
 540         long monthCount = prolepticYear * 12L + (monthOfYear - 1);
 541         long calcMonths = monthCount + monthsToAdd;  // safe overflow
 542         int newYear = chrono.checkValidYear(Math.floorDiv(calcMonths, 12L));
 543         int newMonth = (int)Math.floorMod(calcMonths, 12L) + 1;
 544         return resolvePreviousValid(newYear, newMonth, dayOfMonth);
 545     }
 546 
 547     @Override
 548     HijrahDate plusWeeks(long weeksToAdd) {
 549         return super.plusWeeks(weeksToAdd);
 550     }
 551 
 552     @Override
 553     HijrahDate plusDays(long days) {
 554         return new HijrahDate(chrono, toEpochDay() + days);
 555     }
 556 
 557     @Override
 558     public HijrahDate plus(long amountToAdd, TemporalUnit unit) {
 559         return super.plus(amountToAdd, unit);
 560     }
 561 
 562     @Override
 563     public HijrahDate minus(long amountToSubtract, TemporalUnit unit) {
 564         return super.minus(amountToSubtract, unit);
 565     }
 566 
 567     @Override
 568     HijrahDate minusYears(long yearsToSubtract) {
 569         return super.minusYears(yearsToSubtract);
 570     }
 571 
 572     @Override
 573     HijrahDate minusMonths(long monthsToSubtract) {
 574         return super.minusMonths(monthsToSubtract);
 575     }
 576 
 577     @Override
 578     HijrahDate minusWeeks(long weeksToSubtract) {
 579         return super.minusWeeks(weeksToSubtract);
 580     }
 581 
 582     @Override
 583     HijrahDate minusDays(long daysToSubtract) {
 584         return super.minusDays(daysToSubtract);
 585     }
 586 
 587     @Override        // for javadoc and covariant return type
 588     @SuppressWarnings("unchecked")
 589     public final ChronoLocalDateTime<HijrahDate> atTime(LocalTime localTime) {
 590         return (ChronoLocalDateTime<HijrahDate>)super.atTime(localTime);
 591     }
 592 
 593     @Override
 594     public ChronoPeriod until(ChronoLocalDate endDate) {
 595         // TODO: untested
 596         HijrahDate end = getChronology().date(endDate);
 597         long totalMonths = (end.prolepticYear - this.prolepticYear) * 12 + (end.monthOfYear - this.monthOfYear);  // safe
 598         int days = end.dayOfMonth - this.dayOfMonth;
 599         if (totalMonths > 0 && days < 0) {
 600             totalMonths--;
 601             HijrahDate calcDate = this.plusMonths(totalMonths);
 602             days = (int) (end.toEpochDay() - calcDate.toEpochDay());  // safe
 603         } else if (totalMonths < 0 && days > 0) {
 604             totalMonths++;
 605             days -= end.lengthOfMonth();
 606         }
 607         long years = totalMonths / 12;  // safe
 608         int months = (int) (totalMonths % 12);  // safe
 609         return getChronology().period(Math.toIntExact(years), months, days);
 610     }
 611 
 612     //-------------------------------------------------------------------------
 613     /**
 614      * Compares this date to another date, including the chronology.
 615      * <p>
 616      * Compares this {@code HijrahDate} with another ensuring that the date is the same.
 617      * <p>
 618      * Only objects of type {@code HijrahDate} are compared, other types return false.
 619      * To compare the dates of two {@code TemporalAccessor} instances, including dates
 620      * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.
 621      *
 622      * @param obj  the object to check, null returns false
 623      * @return true if this is equal to the other date and the Chronologies are equal
 624      */
 625     @Override  // override for performance
 626     public boolean equals(Object obj) {
 627         if (this == obj) {
 628             return true;
 629         }
 630         if (obj instanceof HijrahDate) {
 631             HijrahDate otherDate = (HijrahDate) obj;
 632             return prolepticYear == otherDate.prolepticYear
 633                 && this.monthOfYear == otherDate.monthOfYear
 634                 && this.dayOfMonth == otherDate.dayOfMonth
 635                 && getChronology().equals(otherDate.getChronology());
 636         }
 637         return false;
 638     }
 639 
 640     /**
 641      * A hash code for this date.
 642      *
 643      * @return a suitable hash code based only on the Chronology and the date
 644      */
 645     @Override  // override for performance
 646     public int hashCode() {
 647         int yearValue = prolepticYear;
 648         int monthValue = monthOfYear;
 649         int dayValue = dayOfMonth;
 650         return getChronology().getId().hashCode() ^ (yearValue & 0xFFFFF800)
 651                 ^ ((yearValue << 11) + (monthValue << 6) + (dayValue));
 652     }
 653 
 654     //-----------------------------------------------------------------------
 655     /**
 656      * Defend against malicious streams.
 657      *
 658      * @param s the stream to read
 659      * @throws InvalidObjectException always
 660      */
 661     @java.io.Serial
 662     private void readObject(ObjectInputStream s) throws InvalidObjectException {
 663         throw new InvalidObjectException("Deserialization via serialization delegate");
 664     }
 665 
 666     /**
 667      * Writes the object using a
 668      * <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.
 669      * @serialData
 670      * <pre>
 671      *  out.writeByte(6);                 // identifies a HijrahDate
 672      *  out.writeObject(chrono);          // the HijrahChronology variant
 673      *  out.writeInt(get(YEAR));
 674      *  out.writeByte(get(MONTH_OF_YEAR));
 675      *  out.writeByte(get(DAY_OF_MONTH));
 676      * </pre>
 677      *
 678      * @return the instance of {@code Ser}, not null
 679      */
 680     @java.io.Serial
 681     private Object writeReplace() {
 682         return new Ser(Ser.HIJRAH_DATE_TYPE, this);
 683     }
 684 
 685     void writeExternal(ObjectOutput out) throws IOException {
 686         // HijrahChronology is implicit in the Hijrah_DATE_TYPE
 687         out.writeObject(getChronology());
 688         out.writeInt(get(YEAR));
 689         out.writeByte(get(MONTH_OF_YEAR));
 690         out.writeByte(get(DAY_OF_MONTH));
 691     }
 692 
 693     static HijrahDate readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
 694         HijrahChronology chrono = (HijrahChronology) in.readObject();
 695         int year = in.readInt();
 696         int month = in.readByte();
 697         int dayOfMonth = in.readByte();
 698         return chrono.date(year, month, dayOfMonth);
 699     }
 700 
 701 }