1 /*
  2  * Copyright (c) 2012, 2019, 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  * <p>
107  * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
108  * class; programmers should treat instances that are
109  * {@linkplain #equals(Object) equal} as interchangeable and should not
110  * use instances for synchronization, or unpredictable behavior may
111  * occur. For example, in a future release, synchronization may fail.
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 @jdk.internal.ValueBased
120 public final class HijrahDate
121         extends ChronoLocalDateImpl<HijrahDate>
122         implements ChronoLocalDate, Serializable {
123 
124     /**
125      * Serialization version.
126      */
127     @java.io.Serial
128     private static final long serialVersionUID = -5207853542612002020L;
129     /**
130      * The Chronology of this HijrahDate.
131      */
132     private final transient HijrahChronology chrono;
133     /**
134      * The proleptic year.
135      */
136     private final transient int prolepticYear;
137     /**
138      * The month-of-year.
139      */
140     private final transient int monthOfYear;
141     /**
142      * The day-of-month.
143      */
144     private final transient int dayOfMonth;
145 
146     //-------------------------------------------------------------------------
147     /**
148      * Obtains an instance of {@code HijrahDate} from the Hijrah proleptic year,
149      * month-of-year and day-of-month.
150      *
151      * @param prolepticYear  the proleptic year to represent in the Hijrah calendar
152      * @param monthOfYear  the month-of-year to represent, from 1 to 12
153      * @param dayOfMonth  the day-of-month to represent, from 1 to 30
154      * @return the Hijrah date, never null
155      * @throws DateTimeException if the value of any field is out of range
156      */
157     static HijrahDate of(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
158         return new HijrahDate(chrono, prolepticYear, monthOfYear, dayOfMonth);
159     }
160 
161     /**
162      * Returns a HijrahDate for the chronology and epochDay.
163      * @param chrono The Hijrah chronology
164      * @param epochDay the epoch day
165      * @return a HijrahDate for the epoch day; non-null
166      */
167     static HijrahDate ofEpochDay(HijrahChronology chrono, long epochDay) {
168         return new HijrahDate(chrono, epochDay);
169     }
170 
171     //-----------------------------------------------------------------------
172     /**
173      * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
174      * in the default time-zone.
175      * <p>
176      * This will query the {@link Clock#systemDefaultZone() system clock} in the default
177      * time-zone to obtain the current date.
178      * <p>
179      * Using this method will prevent the ability to use an alternate clock for testing
180      * because the clock is hard-coded.
181      *
182      * @return the current date using the system clock and default time-zone, not null
183      */
184     public static HijrahDate now() {
185         return now(Clock.systemDefaultZone());
186     }
187 
188     /**
189      * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
190      * in the specified time-zone.
191      * <p>
192      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
193      * Specifying the time-zone avoids dependence on the default time-zone.
194      * <p>
195      * Using this method will prevent the ability to use an alternate clock for testing
196      * because the clock is hard-coded.
197      *
198      * @param zone  the zone ID to use, not null
199      * @return the current date using the system clock, not null
200      */
201     public static HijrahDate now(ZoneId zone) {
202         return now(Clock.system(zone));
203     }
204 
205     /**
206      * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
207      * from the specified clock.
208      * <p>
209      * This will query the specified clock to obtain the current date - today.
210      * Using this method allows the use of an alternate clock for testing.
211      * The alternate clock may be introduced using {@linkplain Clock dependency injection}.
212      *
213      * @param clock  the clock to use, not null
214      * @return the current date, not null
215      * @throws DateTimeException if the current date cannot be obtained
216      */
217     public static HijrahDate now(Clock clock) {
218         return HijrahDate.ofEpochDay(HijrahChronology.INSTANCE, LocalDate.now(clock).toEpochDay());
219     }
220 
221     /**
222      * Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar
223      * from the proleptic-year, month-of-year and day-of-month fields.
224      * <p>
225      * This returns a {@code HijrahDate} with the specified fields.
226      * The day must be valid for the year and month, otherwise an exception will be thrown.
227      *
228      * @param prolepticYear  the Hijrah proleptic-year
229      * @param month  the Hijrah month-of-year, from 1 to 12
230      * @param dayOfMonth  the Hijrah day-of-month, from 1 to 30
231      * @return the date in Hijrah calendar system, not null
232      * @throws DateTimeException if the value of any field is out of range,
233      *  or if the day-of-month is invalid for the month-year
234      */
235     public static HijrahDate of(int prolepticYear, int month, int dayOfMonth) {
236         return HijrahChronology.INSTANCE.date(prolepticYear, month, dayOfMonth);
237     }
238 
239     /**
240      * Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar from a temporal object.
241      * <p>
242      * This obtains a date in the Hijrah calendar system based on the specified temporal.
243      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
244      * which this factory converts to an instance of {@code HijrahDate}.
245      * <p>
246      * The conversion typically uses the {@link ChronoField#EPOCH_DAY EPOCH_DAY}
247      * field, which is standardized across calendar systems.
248      * <p>
249      * This method matches the signature of the functional interface {@link TemporalQuery}
250      * allowing it to be used as a query via method reference, {@code HijrahDate::from}.
251      *
252      * @param temporal  the temporal object to convert, not null
253      * @return the date in Hijrah calendar system, not null
254      * @throws DateTimeException if unable to convert to a {@code HijrahDate}
255      */
256     public static HijrahDate from(TemporalAccessor temporal) {
257         return HijrahChronology.INSTANCE.date(temporal);
258     }
259 
260     //-----------------------------------------------------------------------
261     /**
262      * Constructs an {@code HijrahDate} with the proleptic-year, month-of-year and
263      * day-of-month fields.
264      *
265      * @param chrono The chronology to create the date with
266      * @param prolepticYear the proleptic year
267      * @param monthOfYear the month of year
268      * @param dayOfMonth the day of month
269      */
270     private HijrahDate(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
271         // Computing the Gregorian day checks the valid ranges
272         chrono.getEpochDay(prolepticYear, monthOfYear, dayOfMonth);
273 
274         this.chrono = chrono;
275         this.prolepticYear = prolepticYear;
276         this.monthOfYear = monthOfYear;
277         this.dayOfMonth = dayOfMonth;
278     }
279 
280     /**
281      * Constructs an instance with the Epoch Day.
282      *
283      * @param epochDay  the epochDay
284      */
285     private HijrahDate(HijrahChronology chrono, long epochDay) {
286         int[] dateInfo = chrono.getHijrahDateInfo((int)epochDay);
287 
288         this.chrono = chrono;
289         this.prolepticYear = dateInfo[0];
290         this.monthOfYear = dateInfo[1];
291         this.dayOfMonth = dateInfo[2];
292     }
293 
294     //-----------------------------------------------------------------------
295     /**
296      * Gets the chronology of this date, which is the Hijrah calendar system.
297      * <p>
298      * The {@code Chronology} represents the calendar system in use.
299      * The era and other fields in {@link ChronoField} are defined by the chronology.
300      *
301      * @return the Hijrah chronology, not null
302      */
303     @Override
304     public HijrahChronology getChronology() {
305         return chrono;
306     }
307 
308     /**
309      * Gets the era applicable at this date.
310      * <p>
311      * The Hijrah calendar system has one era, 'AH',
312      * defined by {@link HijrahEra}.
313      *
314      * @return the era applicable at this date, not null
315      */
316     @Override
317     public HijrahEra getEra() {
318         return HijrahEra.AH;
319     }
320 
321     /**
322      * Returns the length of the month represented by this date.
323      * <p>
324      * This returns the length of the month in days.
325      * Month lengths in the Hijrah calendar system vary between 29 and 30 days.
326      *
327      * @return the length of the month in days
328      */
329     @Override
330     public int lengthOfMonth() {
331         return chrono.getMonthLength(prolepticYear, monthOfYear);
332     }
333 
334     /**
335      * Returns the length of the year represented by this date.
336      * <p>
337      * This returns the length of the year in days.
338      * A Hijrah calendar system year is typically shorter than
339      * that of the ISO calendar system.
340      *
341      * @return the length of the year in days
342      */
343     @Override
344     public int lengthOfYear() {
345         return chrono.getYearLength(prolepticYear);
346     }
347 
348     //-----------------------------------------------------------------------
349     @Override
350     public ValueRange range(TemporalField field) {
351         if (field instanceof ChronoField) {
352             if (isSupported(field)) {
353                 ChronoField f = (ChronoField) field;
354                 return switch (f) {
355                     case DAY_OF_MONTH -> ValueRange.of(1, lengthOfMonth());
356                     case DAY_OF_YEAR -> ValueRange.of(1, lengthOfYear());
357                     case ALIGNED_WEEK_OF_MONTH -> ValueRange.of(1, 5); // TODO
358                     // TODO does the limited range of valid years cause years to
359                     // start/end part way through? that would affect range
360                     default -> getChronology().range(f);
361                 };
362             }
363             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
364         }
365         return field.rangeRefinedBy(this);
366     }
367 
368     @Override
369     public long getLong(TemporalField field) {
370         if (field instanceof ChronoField) {
371             return switch ((ChronoField) field) {
372                 case DAY_OF_WEEK                  ->  getDayOfWeek();
373                 case ALIGNED_DAY_OF_WEEK_IN_MONTH ->  ((dayOfMonth - 1) % 7) + 1;
374                 case ALIGNED_DAY_OF_WEEK_IN_YEAR  ->  ((getDayOfYear() - 1) % 7) + 1;
375                 case DAY_OF_MONTH                 ->  this.dayOfMonth;
376                 case DAY_OF_YEAR                  ->  this.getDayOfYear();
377                 case EPOCH_DAY                    ->  toEpochDay();
378                 case ALIGNED_WEEK_OF_MONTH        ->  ((dayOfMonth - 1) / 7) + 1;
379                 case ALIGNED_WEEK_OF_YEAR         ->  ((getDayOfYear() - 1) / 7) + 1;
380                 case MONTH_OF_YEAR                ->  monthOfYear;
381                 case PROLEPTIC_MONTH              ->  getProlepticMonth();
382                 case YEAR_OF_ERA                  ->  prolepticYear;
383                 case YEAR                         ->  prolepticYear;
384                 case ERA                          ->  getEraValue();
385                 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
386             };
387         }
388         return field.getFrom(this);
389     }
390 
391     private long getProlepticMonth() {
392         return prolepticYear * 12L + monthOfYear - 1;
393     }
394 
395     @Override
396     public HijrahDate with(TemporalField field, long newValue) {
397         if (field instanceof ChronoField chronoField) {
398             // not using checkValidIntValue so EPOCH_DAY and PROLEPTIC_MONTH work
399             chrono.range(chronoField).checkValidValue(newValue, chronoField);    // TODO: validate value
400             int nvalue = (int) newValue;
401             return switch (chronoField) {
402                 case DAY_OF_WEEK                  ->  plusDays(newValue - getDayOfWeek());
403                 case ALIGNED_DAY_OF_WEEK_IN_MONTH ->  plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));
404                 case ALIGNED_DAY_OF_WEEK_IN_YEAR  ->  plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));
405                 case DAY_OF_MONTH                 ->  resolvePreviousValid(prolepticYear, monthOfYear, nvalue);
406                 case DAY_OF_YEAR                  ->  plusDays(Math.min(nvalue, lengthOfYear()) - getDayOfYear());
407                 case EPOCH_DAY                    ->  new HijrahDate(chrono, newValue);
408                 case ALIGNED_WEEK_OF_MONTH        ->  plusDays((newValue - getLong(ALIGNED_WEEK_OF_MONTH)) * 7);
409                 case ALIGNED_WEEK_OF_YEAR         ->  plusDays((newValue - getLong(ALIGNED_WEEK_OF_YEAR)) * 7);
410                 case MONTH_OF_YEAR                ->  resolvePreviousValid(prolepticYear, nvalue, dayOfMonth);
411                 case PROLEPTIC_MONTH              ->  plusMonths(newValue - getProlepticMonth());
412                 case YEAR_OF_ERA                  ->  resolvePreviousValid(prolepticYear >= 1 ? nvalue : 1 - nvalue, monthOfYear, dayOfMonth);
413                 case YEAR                         ->  resolvePreviousValid(nvalue, monthOfYear, dayOfMonth);
414                 case ERA                          ->  resolvePreviousValid(1 - prolepticYear, monthOfYear, dayOfMonth);
415                 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
416             };
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         return (obj instanceof HijrahDate otherDate)
631                 && prolepticYear == otherDate.prolepticYear
632                 && this.monthOfYear == otherDate.monthOfYear
633                 && this.dayOfMonth == otherDate.dayOfMonth
634                 && getChronology().equals(otherDate.getChronology());
635     }
636 
637     /**
638      * A hash code for this date.
639      *
640      * @return a suitable hash code based only on the Chronology and the date
641      */
642     @Override  // override for performance
643     public int hashCode() {
644         int yearValue = prolepticYear;
645         int monthValue = monthOfYear;
646         int dayValue = dayOfMonth;
647         return getChronology().getId().hashCode() ^ (yearValue & 0xFFFFF800)
648                 ^ ((yearValue << 11) + (monthValue << 6) + (dayValue));
649     }
650 
651     //-----------------------------------------------------------------------
652     /**
653      * Defend against malicious streams.
654      *
655      * @param s the stream to read
656      * @throws InvalidObjectException always
657      */
658     @java.io.Serial
659     private void readObject(ObjectInputStream s) throws InvalidObjectException {
660         throw new InvalidObjectException("Deserialization via serialization delegate");
661     }
662 
663     /**
664      * Writes the object using a
665      * <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.
666      * @serialData
667      * <pre>
668      *  out.writeByte(6);                 // identifies a HijrahDate
669      *  out.writeObject(chrono);          // the HijrahChronology variant
670      *  out.writeInt(get(YEAR));
671      *  out.writeByte(get(MONTH_OF_YEAR));
672      *  out.writeByte(get(DAY_OF_MONTH));
673      * </pre>
674      *
675      * @return the instance of {@code Ser}, not null
676      */
677     @java.io.Serial
678     private Object writeReplace() {
679         return new Ser(Ser.HIJRAH_DATE_TYPE, this);
680     }
681 
682     void writeExternal(ObjectOutput out) throws IOException {
683         // HijrahChronology is implicit in the Hijrah_DATE_TYPE
684         out.writeObject(getChronology());
685         out.writeInt(get(YEAR));
686         out.writeByte(get(MONTH_OF_YEAR));
687         out.writeByte(get(DAY_OF_MONTH));
688     }
689 
690     static HijrahDate readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
691         HijrahChronology chrono = (HijrahChronology) in.readObject();
692         int year = in.readInt();
693         int month = in.readByte();
694         int dayOfMonth = in.readByte();
695         return chrono.date(year, month, dayOfMonth);
696     }
697 
698 }