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