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 {@linkplain #equals(Object) equal}
109 * as interchangeable and should not use instances for synchronization, mutexes, or
110 * with {@linkplain java.lang.ref.Reference object references}.
111 *
112 * <div class="preview-block">
113 * <div class="preview-comment">
114 * When preview features are enabled, {@code HijrahDate} is a {@linkplain Class#isValue value class}.
115 * Use of value class instances for synchronization, mutexes, or with
116 * {@linkplain java.lang.ref.Reference object references} result in
117 * {@link IdentityException}.
118 * </div>
119 * </div>
120 *
121 * @implSpec
122 * This class is immutable and thread-safe.
123 *
124 * @since 1.8
125 */
126 @jdk.internal.ValueBased
127 @jdk.internal.MigratedValueClass
128 public final class HijrahDate
129 extends ChronoLocalDateImpl<HijrahDate>
130 implements ChronoLocalDate, Serializable {
131
132 /**
133 * Serialization version.
134 */
135 @java.io.Serial
136 private static final long serialVersionUID = -5207853542612002020L;
137 /**
138 * The Chronology of this HijrahDate.
139 */
140 private final transient HijrahChronology chrono;
141 /**
142 * The proleptic year.
143 */
144 private final transient int prolepticYear;
145 /**
146 * The month-of-year.
147 */
148 private final transient int monthOfYear;
149 /**
150 * The day-of-month.
151 */
152 private final transient int dayOfMonth;
153
154 //-------------------------------------------------------------------------
155 /**
156 * Obtains an instance of {@code HijrahDate} from the Hijrah proleptic year,
157 * month-of-year and day-of-month.
158 *
159 * @param prolepticYear the proleptic year to represent in the Hijrah calendar
160 * @param monthOfYear the month-of-year to represent, from 1 to 12
161 * @param dayOfMonth the day-of-month to represent, from 1 to 30
162 * @return the Hijrah date, never null
163 * @throws DateTimeException if the value of any field is out of range
164 */
165 static HijrahDate of(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
166 return new HijrahDate(chrono, prolepticYear, monthOfYear, dayOfMonth);
167 }
168
169 /**
170 * Returns a HijrahDate for the chronology and epochDay.
171 * @param chrono The Hijrah chronology
172 * @param epochDay the epoch day
173 * @return a HijrahDate for the epoch day; non-null
174 */
175 static HijrahDate ofEpochDay(HijrahChronology chrono, long epochDay) {
176 return new HijrahDate(chrono, epochDay);
177 }
178
179 //-----------------------------------------------------------------------
180 /**
181 * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
182 * in the default time-zone.
183 * <p>
184 * This will query the {@link Clock#systemDefaultZone() system clock} in the default
185 * time-zone to obtain the current date.
186 * <p>
187 * Using this method will prevent the ability to use an alternate clock for testing
188 * because the clock is hard-coded.
189 *
190 * @return the current date using the system clock and default time-zone, not null
191 */
192 public static HijrahDate now() {
193 return now(Clock.systemDefaultZone());
194 }
195
196 /**
197 * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
198 * in the specified time-zone.
199 * <p>
200 * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
201 * Specifying the time-zone avoids dependence on the default time-zone.
202 * <p>
203 * Using this method will prevent the ability to use an alternate clock for testing
204 * because the clock is hard-coded.
205 *
206 * @param zone the zone ID to use, not null
207 * @return the current date using the system clock, not null
208 */
209 public static HijrahDate now(ZoneId zone) {
210 return now(Clock.system(zone));
211 }
212
213 /**
214 * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
215 * from the specified clock.
216 * <p>
217 * This will query the specified clock to obtain the current date - today.
218 * Using this method allows the use of an alternate clock for testing.
219 * The alternate clock may be introduced using {@linkplain Clock dependency injection}.
220 *
221 * @param clock the clock to use, not null
222 * @return the current date, not null
223 * @throws DateTimeException if the current date cannot be obtained
224 */
225 public static HijrahDate now(Clock clock) {
226 return HijrahDate.ofEpochDay(HijrahChronology.INSTANCE, LocalDate.now(clock).toEpochDay());
227 }
228
229 /**
230 * Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar
231 * from the proleptic-year, month-of-year and day-of-month fields.
232 * <p>
233 * This returns a {@code HijrahDate} with the specified fields.
234 * The day must be valid for the year and month, otherwise an exception will be thrown.
235 *
236 * @param prolepticYear the Hijrah proleptic-year
237 * @param month the Hijrah month-of-year, from 1 to 12
238 * @param dayOfMonth the Hijrah day-of-month, from 1 to 30
239 * @return the date in Hijrah calendar system, not null
240 * @throws DateTimeException if the value of any field is out of range,
241 * or if the day-of-month is invalid for the month-year
242 */
243 public static HijrahDate of(int prolepticYear, int month, int dayOfMonth) {
244 return HijrahChronology.INSTANCE.date(prolepticYear, month, dayOfMonth);
245 }
246
247 /**
248 * Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar from a temporal object.
249 * <p>
250 * This obtains a date in the Hijrah calendar system based on the specified temporal.
251 * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
252 * which this factory converts to an instance of {@code HijrahDate}.
253 * <p>
254 * The conversion typically uses the {@link ChronoField#EPOCH_DAY EPOCH_DAY}
255 * field, which is standardized across calendar systems.
256 * <p>
257 * This method matches the signature of the functional interface {@link TemporalQuery}
258 * allowing it to be used as a query via method reference, {@code HijrahDate::from}.
259 *
260 * @param temporal the temporal object to convert, not null
261 * @return the date in Hijrah calendar system, not null
262 * @throws DateTimeException if unable to convert to a {@code HijrahDate}
263 */
264 public static HijrahDate from(TemporalAccessor temporal) {
265 return HijrahChronology.INSTANCE.date(temporal);
266 }
267
268 //-----------------------------------------------------------------------
269 /**
270 * Constructs an {@code HijrahDate} with the proleptic-year, month-of-year and
271 * day-of-month fields.
272 *
273 * @param chrono The chronology to create the date with
274 * @param prolepticYear the proleptic year
275 * @param monthOfYear the month of year
276 * @param dayOfMonth the day of month
277 */
278 private HijrahDate(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
279 // Computing the Gregorian day checks the valid ranges
280 chrono.getEpochDay(prolepticYear, monthOfYear, dayOfMonth);
281
282 this.chrono = chrono;
283 this.prolepticYear = prolepticYear;
284 this.monthOfYear = monthOfYear;
285 this.dayOfMonth = dayOfMonth;
286 }
287
288 /**
289 * Constructs an instance with the Epoch Day.
290 *
291 * @param epochDay the epochDay
292 */
293 private HijrahDate(HijrahChronology chrono, long epochDay) {
294 int[] dateInfo = chrono.getHijrahDateInfo((int)epochDay);
295
296 this.chrono = chrono;
297 this.prolepticYear = dateInfo[0];
298 this.monthOfYear = dateInfo[1];
299 this.dayOfMonth = dateInfo[2];
300 }
301
302 //-----------------------------------------------------------------------
303 /**
304 * Gets the chronology of this date, which is the Hijrah calendar system.
305 * <p>
306 * The {@code Chronology} represents the calendar system in use.
307 * The era and other fields in {@link ChronoField} are defined by the chronology.
308 *
309 * @return the Hijrah chronology, not null
310 */
311 @Override
312 public HijrahChronology getChronology() {
313 return chrono;
314 }
315
316 /**
317 * Gets the era applicable at this date.
318 * <p>
319 * The Hijrah calendar system has one era, 'AH',
320 * defined by {@link HijrahEra}.
321 *
322 * @return the era applicable at this date, not null
323 */
324 @Override
325 public HijrahEra getEra() {
326 return HijrahEra.AH;
327 }
328
329 /**
330 * Returns the length of the month represented by this date.
331 * <p>
332 * This returns the length of the month in days.
333 * Month lengths in the Hijrah calendar system vary between 29 and 30 days.
334 *
335 * @return the length of the month in days
336 */
337 @Override
338 public int lengthOfMonth() {
339 return chrono.getMonthLength(prolepticYear, monthOfYear);
340 }
341
342 /**
343 * Returns the length of the year represented by this date.
344 * <p>
345 * This returns the length of the year in days.
346 * A Hijrah calendar system year is typically shorter than
347 * that of the ISO calendar system.
348 *
349 * @return the length of the year in days
350 */
351 @Override
352 public int lengthOfYear() {
353 return chrono.getYearLength(prolepticYear);
354 }
355
356 //-----------------------------------------------------------------------
357 @Override
358 public ValueRange range(TemporalField field) {
359 if (field instanceof ChronoField) {
360 if (isSupported(field)) {
361 ChronoField f = (ChronoField) field;
362 return switch (f) {
363 case DAY_OF_MONTH -> ValueRange.of(1, lengthOfMonth());
364 case DAY_OF_YEAR -> ValueRange.of(1, lengthOfYear());
365 case ALIGNED_WEEK_OF_MONTH -> ValueRange.of(1, 5); // TODO
366 // TODO does the limited range of valid years cause years to
367 // start/end part way through? that would affect range
368 default -> getChronology().range(f);
369 };
370 }
371 throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
372 }
373 return field.rangeRefinedBy(this);
374 }
375
376 @Override
377 public long getLong(TemporalField field) {
378 if (field instanceof ChronoField) {
379 return switch ((ChronoField) field) {
380 case DAY_OF_WEEK -> getDayOfWeek();
381 case ALIGNED_DAY_OF_WEEK_IN_MONTH -> ((dayOfMonth - 1) % 7) + 1;
382 case ALIGNED_DAY_OF_WEEK_IN_YEAR -> ((getDayOfYear() - 1) % 7) + 1;
383 case DAY_OF_MONTH -> this.dayOfMonth;
384 case DAY_OF_YEAR -> this.getDayOfYear();
385 case EPOCH_DAY -> toEpochDay();
386 case ALIGNED_WEEK_OF_MONTH -> ((dayOfMonth - 1) / 7) + 1;
387 case ALIGNED_WEEK_OF_YEAR -> ((getDayOfYear() - 1) / 7) + 1;
388 case MONTH_OF_YEAR -> monthOfYear;
389 case PROLEPTIC_MONTH -> getProlepticMonth();
390 case YEAR_OF_ERA -> prolepticYear;
391 case YEAR -> prolepticYear;
392 case ERA -> getEraValue();
393 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
394 };
395 }
396 return field.getFrom(this);
397 }
398
399 private long getProlepticMonth() {
400 return prolepticYear * 12L + monthOfYear - 1;
401 }
402
403 @Override
404 public HijrahDate with(TemporalField field, long newValue) {
405 if (field instanceof ChronoField chronoField) {
406 // not using checkValidIntValue so EPOCH_DAY and PROLEPTIC_MONTH work
407 chrono.range(chronoField).checkValidValue(newValue, chronoField); // TODO: validate value
408 int nvalue = (int) newValue;
409 return switch (chronoField) {
410 case DAY_OF_WEEK -> plusDays(newValue - getDayOfWeek());
411 case ALIGNED_DAY_OF_WEEK_IN_MONTH -> plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));
412 case ALIGNED_DAY_OF_WEEK_IN_YEAR -> plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));
413 case DAY_OF_MONTH -> resolvePreviousValid(prolepticYear, monthOfYear, nvalue);
414 case DAY_OF_YEAR -> plusDays(Math.min(nvalue, lengthOfYear()) - getDayOfYear());
415 case EPOCH_DAY -> new HijrahDate(chrono, newValue);
416 case ALIGNED_WEEK_OF_MONTH -> plusDays((newValue - getLong(ALIGNED_WEEK_OF_MONTH)) * 7);
417 case ALIGNED_WEEK_OF_YEAR -> plusDays((newValue - getLong(ALIGNED_WEEK_OF_YEAR)) * 7);
418 case MONTH_OF_YEAR -> resolvePreviousValid(prolepticYear, nvalue, dayOfMonth);
419 case PROLEPTIC_MONTH -> plusMonths(newValue - getProlepticMonth());
420 case YEAR_OF_ERA -> resolvePreviousValid(prolepticYear >= 1 ? nvalue : 1 - nvalue, monthOfYear, dayOfMonth);
421 case YEAR -> resolvePreviousValid(nvalue, monthOfYear, dayOfMonth);
422 case ERA -> resolvePreviousValid(1 - prolepticYear, monthOfYear, dayOfMonth);
423 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
424 };
425 }
426 return super.with(field, newValue);
427 }
428
429 private HijrahDate resolvePreviousValid(int prolepticYear, int month, int day) {
430 int monthDays = chrono.getMonthLength(prolepticYear, month);
431 if (day > monthDays) {
432 day = monthDays;
433 }
434 return HijrahDate.of(chrono, prolepticYear, month, day);
435 }
436
437 /**
438 * {@inheritDoc}
439 * @throws DateTimeException if unable to make the adjustment.
440 * For example, if the adjuster requires an ISO chronology
441 * @throws ArithmeticException {@inheritDoc}
442 */
443 @Override
444 public HijrahDate with(TemporalAdjuster adjuster) {
445 return super.with(adjuster);
446 }
447
448 /**
449 * Returns a {@code HijrahDate} with the Chronology requested.
450 * <p>
451 * The year, month, and day are checked against the new requested
452 * HijrahChronology. If the chronology has a shorter month length
453 * for the month, the day is reduced to be the last day of the month.
454 *
455 * @param chronology the new HijrahChonology, non-null
456 * @return a HijrahDate with the requested HijrahChronology, non-null
457 */
458 public HijrahDate withVariant(HijrahChronology chronology) {
459 if (chrono == chronology) {
460 return this;
461 }
462 // Like resolvePreviousValid the day is constrained to stay in the same month
463 int monthDays = chronology.getDayOfYear(prolepticYear, monthOfYear);
464 return HijrahDate.of(chronology, prolepticYear, monthOfYear,(dayOfMonth > monthDays) ? monthDays : dayOfMonth );
465 }
466
467 /**
468 * {@inheritDoc}
469 * @throws DateTimeException {@inheritDoc}
470 * @throws ArithmeticException {@inheritDoc}
471 */
472 @Override
473 public HijrahDate plus(TemporalAmount amount) {
474 return super.plus(amount);
475 }
476
477 /**
478 * {@inheritDoc}
479 * @throws DateTimeException {@inheritDoc}
480 * @throws ArithmeticException {@inheritDoc}
481 */
482 @Override
483 public HijrahDate minus(TemporalAmount amount) {
484 return super.minus(amount);
485 }
486
487 @Override
488 public long toEpochDay() {
489 return chrono.getEpochDay(prolepticYear, monthOfYear, dayOfMonth);
490 }
491
492 /**
493 * Gets the day-of-year field.
494 * <p>
495 * This method returns the primitive {@code int} value for the day-of-year.
496 *
497 * @return the day-of-year
498 */
499 private int getDayOfYear() {
500 return chrono.getDayOfYear(prolepticYear, monthOfYear) + dayOfMonth;
501 }
502
503 /**
504 * Gets the day-of-week value.
505 *
506 * @return the day-of-week; computed from the epochday
507 */
508 private int getDayOfWeek() {
509 int dow0 = Math.floorMod(toEpochDay() + 3, 7);
510 return dow0 + 1;
511 }
512
513 /**
514 * Gets the Era of this date.
515 *
516 * @return the Era of this date; computed from epochDay
517 */
518 private int getEraValue() {
519 return (prolepticYear > 1 ? 1 : 0);
520 }
521
522 //-----------------------------------------------------------------------
523 /**
524 * Checks if the year is a leap year, according to the Hijrah calendar system rules.
525 *
526 * @return true if this date is in a leap year
527 */
528 @Override
529 public boolean isLeapYear() {
530 return chrono.isLeapYear(prolepticYear);
531 }
532
533 //-----------------------------------------------------------------------
534 @Override
535 HijrahDate plusYears(long years) {
536 if (years == 0) {
537 return this;
538 }
539 int newYear = Math.addExact(this.prolepticYear, (int)years);
540 return resolvePreviousValid(newYear, monthOfYear, dayOfMonth);
541 }
542
543 @Override
544 HijrahDate plusMonths(long monthsToAdd) {
545 if (monthsToAdd == 0) {
546 return this;
547 }
548 long monthCount = prolepticYear * 12L + (monthOfYear - 1);
549 long calcMonths = monthCount + monthsToAdd; // safe overflow
550 int newYear = chrono.checkValidYear(Math.floorDiv(calcMonths, 12L));
551 int newMonth = (int)Math.floorMod(calcMonths, 12L) + 1;
552 return resolvePreviousValid(newYear, newMonth, dayOfMonth);
553 }
554
555 @Override
556 HijrahDate plusWeeks(long weeksToAdd) {
557 return super.plusWeeks(weeksToAdd);
558 }
559
560 @Override
561 HijrahDate plusDays(long days) {
562 return new HijrahDate(chrono, toEpochDay() + days);
563 }
564
565 @Override
566 public HijrahDate plus(long amountToAdd, TemporalUnit unit) {
567 return super.plus(amountToAdd, unit);
568 }
569
570 @Override
571 public HijrahDate minus(long amountToSubtract, TemporalUnit unit) {
572 return super.minus(amountToSubtract, unit);
573 }
574
575 @Override
576 HijrahDate minusYears(long yearsToSubtract) {
577 return super.minusYears(yearsToSubtract);
578 }
579
580 @Override
581 HijrahDate minusMonths(long monthsToSubtract) {
582 return super.minusMonths(monthsToSubtract);
583 }
584
585 @Override
586 HijrahDate minusWeeks(long weeksToSubtract) {
587 return super.minusWeeks(weeksToSubtract);
588 }
589
590 @Override
591 HijrahDate minusDays(long daysToSubtract) {
592 return super.minusDays(daysToSubtract);
593 }
594
595 @Override // for javadoc and covariant return type
596 @SuppressWarnings("unchecked")
597 public final ChronoLocalDateTime<HijrahDate> atTime(LocalTime localTime) {
598 return (ChronoLocalDateTime<HijrahDate>)super.atTime(localTime);
599 }
600
601 @Override
602 public ChronoPeriod until(ChronoLocalDate endDate) {
603 // TODO: untested
604 HijrahDate end = getChronology().date(endDate);
605 long totalMonths = (end.prolepticYear - this.prolepticYear) * 12 + (end.monthOfYear - this.monthOfYear); // safe
606 int days = end.dayOfMonth - this.dayOfMonth;
607 if (totalMonths > 0 && days < 0) {
608 totalMonths--;
609 HijrahDate calcDate = this.plusMonths(totalMonths);
610 days = (int) (end.toEpochDay() - calcDate.toEpochDay()); // safe
611 } else if (totalMonths < 0 && days > 0) {
612 totalMonths++;
613 days -= end.lengthOfMonth();
614 }
615 long years = totalMonths / 12; // safe
616 int months = (int) (totalMonths % 12); // safe
617 return getChronology().period(Math.toIntExact(years), months, days);
618 }
619
620 //-------------------------------------------------------------------------
621 /**
622 * Compares this date to another date, including the chronology.
623 * <p>
624 * Compares this {@code HijrahDate} with another ensuring that the date is the same.
625 * <p>
626 * Only objects of type {@code HijrahDate} are compared, other types return false.
627 * To compare the dates of two {@code TemporalAccessor} instances, including dates
628 * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.
629 *
630 * @param obj the object to check, null returns false
631 * @return true if this is equal to the other date and the Chronologies are equal
632 */
633 @Override // override for performance
634 public boolean equals(Object obj) {
635 if (this == obj) {
636 return true;
637 }
638 return (obj instanceof HijrahDate otherDate)
639 && prolepticYear == otherDate.prolepticYear
640 && this.monthOfYear == otherDate.monthOfYear
641 && this.dayOfMonth == otherDate.dayOfMonth
642 && getChronology().equals(otherDate.getChronology());
643 }
644
645 /**
646 * A hash code for this date.
647 *
648 * @return a suitable hash code based only on the Chronology and the date
649 */
650 @Override // override for performance
651 public int hashCode() {
652 int yearValue = prolepticYear;
653 int monthValue = monthOfYear;
654 int dayValue = dayOfMonth;
655 return getChronology().getId().hashCode() ^ (yearValue & 0xFFFFF800)
656 ^ ((yearValue << 11) + (monthValue << 6) + (dayValue));
657 }
658
659 //-----------------------------------------------------------------------
660 /**
661 * Defend against malicious streams.
662 *
663 * @param s the stream to read
664 * @throws InvalidObjectException always
665 */
666 @java.io.Serial
667 private void readObject(ObjectInputStream s) throws InvalidObjectException {
668 throw new InvalidObjectException("Deserialization via serialization delegate");
669 }
670
671 /**
672 * Writes the object using a
673 * <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.
674 * @serialData
675 * <pre>
676 * out.writeByte(6); // identifies a HijrahDate
677 * out.writeObject(chrono); // the HijrahChronology variant
678 * out.writeInt(get(YEAR));
679 * out.writeByte(get(MONTH_OF_YEAR));
680 * out.writeByte(get(DAY_OF_MONTH));
681 * </pre>
682 *
683 * @return the instance of {@code Ser}, not null
684 */
685 @java.io.Serial
686 private Object writeReplace() {
687 return new Ser(Ser.HIJRAH_DATE_TYPE, this);
688 }
689
690 void writeExternal(ObjectOutput out) throws IOException {
691 // HijrahChronology is implicit in the Hijrah_DATE_TYPE
692 out.writeObject(getChronology());
693 out.writeInt(get(YEAR));
694 out.writeByte(get(MONTH_OF_YEAR));
695 out.writeByte(get(DAY_OF_MONTH));
696 }
697
698 static HijrahDate readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
699 HijrahChronology chrono = (HijrahChronology) in.readObject();
700 int year = in.readInt();
701 int month = in.readByte();
702 int dayOfMonth = in.readByte();
703 return chrono.date(year, month, dayOfMonth);
704 }
705
706 }