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