HijrahDate.java 24.1 KB
Newer Older
S
sherman 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
/*
 * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of JSR-310 nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
S
sherman 已提交
57
package java.time.chrono;
S
sherman 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70

import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.YEAR;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
S
sherman 已提交
71
import java.time.Clock;
S
sherman 已提交
72 73
import java.time.DateTimeException;
import java.time.LocalDate;
S
sherman 已提交
74 75 76
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
S
sherman 已提交
77
import java.time.temporal.ChronoField;
S
sherman 已提交
78 79 80
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAmount;
S
sherman 已提交
81
import java.time.temporal.TemporalField;
82
import java.time.temporal.TemporalQuery;
S
sherman 已提交
83
import java.time.temporal.TemporalUnit;
84
import java.time.temporal.UnsupportedTemporalTypeException;
S
sherman 已提交
85 86 87 88 89
import java.time.temporal.ValueRange;

/**
 * A date in the Hijrah calendar system.
 * <p>
90 91
 * This date operates using one of several variants of the
 * {@linkplain HijrahChronology Hijrah calendar}.
S
sherman 已提交
92 93
 * <p>
 * The Hijrah calendar has a different total of days in a year than
94 95 96 97
 * Gregorian calendar, and the length of each month is based on the period
 * of a complete revolution of the moon around the earth
 * (as between successive new moons).
 * Refer to the {@link HijrahChronology} for details of supported variants.
S
sherman 已提交
98
 * <p>
99 100 101 102 103 104
 * Each HijrahDate is created bound to a particular HijrahChronology,
 * The same chronology is propagated to each HijrahDate computed from the date.
 * To use a different Hijrah variant, its HijrahChronology can be used
 * to create new HijrahDate instances.
 * Alternatively, the {@link #withVariant} method can be used to convert
 * to a new HijrahChronology.
S
sherman 已提交
105 106 107 108 109
 * <h3>Specification for implementors</h3>
 * This class is immutable and thread-safe.
 *
 * @since 1.8
 */
S
sherman 已提交
110 111 112
public final class HijrahDate
        extends ChronoDateImpl<HijrahDate>
        implements ChronoLocalDate<HijrahDate>, Serializable {
S
sherman 已提交
113 114 115 116 117 118 119 120

    /**
     * Serialization version.
     */
    private static final long serialVersionUID = -5207853542612002020L;
    /**
     * The Chronology of this HijrahDate.
     */
S
sherman 已提交
121
    private final HijrahChronology chrono;
S
sherman 已提交
122
    /**
123
     * The proleptic year.
S
sherman 已提交
124
     */
125
    private final transient int prolepticYear;
S
sherman 已提交
126 127 128 129 130 131 132 133 134 135 136
    /**
     * The month-of-year.
     */
    private final transient int monthOfYear;
    /**
     * The day-of-month.
     */
    private final transient int dayOfMonth;

    //-------------------------------------------------------------------------
    /**
137 138
     * Obtains an instance of {@code HijrahDate} from the Hijrah proleptic year,
     * month-of-year and day-of-month.
S
sherman 已提交
139
     *
140
     * @param prolepticYear  the proleptic year to represent in the Hijrah calendar
S
sherman 已提交
141 142 143 144 145
     * @param monthOfYear  the month-of-year to represent, from 1 to 12
     * @param dayOfMonth  the day-of-month to represent, from 1 to 30
     * @return the Hijrah date, never null
     * @throws DateTimeException if the value of any field is out of range
     */
S
sherman 已提交
146
    static HijrahDate of(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
147
        return new HijrahDate(chrono, prolepticYear, monthOfYear, dayOfMonth);
S
sherman 已提交
148 149 150
    }

    /**
151 152 153 154
     * Returns a HijrahDate for the chronology and epochDay.
     * @param chrono The Hijrah chronology
     * @param epochDay the epoch day
     * @return a HijrahDate for the epoch day; non-null
S
sherman 已提交
155
     */
S
sherman 已提交
156 157 158 159 160
    static HijrahDate ofEpochDay(HijrahChronology chrono, long epochDay) {
        return new HijrahDate(chrono, epochDay);
    }

    //-----------------------------------------------------------------------
S
sherman 已提交
161
    /**
162 163
     * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
     * in the default time-zone.
S
sherman 已提交
164 165 166 167 168 169
     * <p>
     * This will query the {@link Clock#systemDefaultZone() system clock} in the default
     * time-zone to obtain the current date.
     * <p>
     * Using this method will prevent the ability to use an alternate clock for testing
     * because the clock is hard-coded.
S
sherman 已提交
170
     *
S
sherman 已提交
171
     * @return the current date using the system clock and default time-zone, not null
S
sherman 已提交
172
     */
S
sherman 已提交
173 174
    public static HijrahDate now() {
        return now(Clock.systemDefaultZone());
S
sherman 已提交
175 176
    }

S
sherman 已提交
177
    /**
178 179
     * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
     * in the specified time-zone.
S
sherman 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
     * <p>
     * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
     * Specifying the time-zone avoids dependence on the default time-zone.
     * <p>
     * Using this method will prevent the ability to use an alternate clock for testing
     * because the clock is hard-coded.
     *
     * @param zone  the zone ID to use, not null
     * @return the current date using the system clock, not null
     */
    public static HijrahDate now(ZoneId zone) {
        return now(Clock.system(zone));
    }

    /**
195 196
     * Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
     * from the specified clock.
S
sherman 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210
     * <p>
     * This will query the specified clock to obtain the current date - today.
     * Using this method allows the use of an alternate clock for testing.
     * The alternate clock may be introduced using {@linkplain Clock dependency injection}.
     *
     * @param clock  the clock to use, not null
     * @return the current date, not null
     * @throws DateTimeException if the current date cannot be obtained
     */
    public static HijrahDate now(Clock clock) {
        return HijrahChronology.INSTANCE.date(LocalDate.now(clock));
    }

    /**
211 212
     * Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar
     * from the proleptic-year, month-of-year and day-of-month fields.
S
sherman 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225
     * <p>
     * This returns a {@code HijrahDate} with the specified fields.
     * The day must be valid for the year and month, otherwise an exception will be thrown.
     *
     * @param prolepticYear  the Hijrah proleptic-year
     * @param month  the Hijrah month-of-year, from 1 to 12
     * @param dayOfMonth  the Hijrah day-of-month, from 1 to 30
     * @return the date in Hijrah calendar system, not null
     * @throws DateTimeException if the value of any field is out of range,
     *  or if the day-of-month is invalid for the month-year
     */
    public static HijrahDate of(int prolepticYear, int month, int dayOfMonth) {
        return HijrahChronology.INSTANCE.date(prolepticYear, month, dayOfMonth);
S
sherman 已提交
226 227
    }

S
sherman 已提交
228
    /**
229
     * Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar from a temporal object.
S
sherman 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
     * <p>
     * This obtains a date in the Hijrah calendar system based on the specified temporal.
     * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
     * which this factory converts to an instance of {@code HijrahDate}.
     * <p>
     * The conversion typically uses the {@link ChronoField#EPOCH_DAY EPOCH_DAY}
     * field, which is standardized across calendar systems.
     * <p>
     * This method matches the signature of the functional interface {@link TemporalQuery}
     * allowing it to be used as a query via method reference, {@code HijrahDate::from}.
     *
     * @param temporal  the temporal object to convert, not null
     * @return the date in Hijrah calendar system, not null
     * @throws DateTimeException if unable to convert to a {@code HijrahDate}
     */
    public static HijrahDate from(TemporalAccessor temporal) {
        return HijrahChronology.INSTANCE.date(temporal);
    }

    //-----------------------------------------------------------------------
S
sherman 已提交
250
    /**
251 252
     * Constructs an {@code HijrahDate} with the proleptic-year, month-of-year and
     * day-of-month fields.
S
sherman 已提交
253
     *
254 255 256 257
     * @param chrono The chronology to create the date with
     * @param prolepticYear the proleptic year
     * @param monthOfYear the month of year
     * @param dayOfMonth the day of month
S
sherman 已提交
258
     */
259 260 261 262
    private HijrahDate(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
        // Computing the Gregorian day checks the valid ranges
        chrono.getEpochDay(prolepticYear, monthOfYear, dayOfMonth);

S
sherman 已提交
263
        this.chrono = chrono;
264 265 266 267
        this.prolepticYear = prolepticYear;
        this.monthOfYear = monthOfYear;
        this.dayOfMonth = dayOfMonth;
    }
S
sherman 已提交
268

269 270 271 272 273 274 275
    /**
     * Constructs an instance with the Epoch Day.
     *
     * @param epochDay  the epochDay
     */
    private HijrahDate(HijrahChronology chrono, long epochDay) {
        int[] dateInfo = chrono.getHijrahDateInfo((int)epochDay);
S
sherman 已提交
276

277 278 279 280
        this.chrono = chrono;
        this.prolepticYear = dateInfo[0];
        this.monthOfYear = dateInfo[1];
        this.dayOfMonth = dateInfo[2];
S
sherman 已提交
281 282 283
    }

    //-----------------------------------------------------------------------
284 285 286 287 288 289 290 291
    /**
     * Gets the chronology of this date, which is the Hijrah calendar system.
     * <p>
     * The {@code Chronology} represents the calendar system in use.
     * The era and other fields in {@link ChronoField} are defined by the chronology.
     *
     * @return the Hijrah chronology, not null
     */
S
sherman 已提交
292
    @Override
S
sherman 已提交
293
    public HijrahChronology getChronology() {
S
sherman 已提交
294 295 296
        return chrono;
    }

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    /**
     * Gets the era applicable at this date.
     * <p>
     * The Hijrah calendar system has one era, 'AH',
     * defined by {@link HijrahEra}.
     *
     * @return the era applicable at this date, not null
     */
    @Override
    public HijrahEra getEra() {
        return HijrahEra.AH;
    }

    /**
     * Returns the length of the month represented by this date.
     * <p>
     * This returns the length of the month in days.
     * Month lengths in the Hijrah calendar system vary between 29 and 30 days.
     *
     * @return the length of the month in days
     */
    @Override
    public int lengthOfMonth() {
        return chrono.getMonthLength(prolepticYear, monthOfYear);
    }

    /**
     * Returns the length of the year represented by this date.
     * <p>
     * This returns the length of the year in days.
     * A Hijrah calendar system year is typically shorter than
     * that of the ISO calendar system.
     *
     * @return the length of the year in days
     */
    @Override
    public int lengthOfYear() {
        return chrono.getYearLength(prolepticYear);
    }

    //-----------------------------------------------------------------------
S
sherman 已提交
338 339 340 341 342 343 344 345 346
    @Override
    public ValueRange range(TemporalField field) {
        if (field instanceof ChronoField) {
            if (isSupported(field)) {
                ChronoField f = (ChronoField) field;
                switch (f) {
                    case DAY_OF_MONTH: return ValueRange.of(1, lengthOfMonth());
                    case DAY_OF_YEAR: return ValueRange.of(1, lengthOfYear());
                    case ALIGNED_WEEK_OF_MONTH: return ValueRange.of(1, 5);  // TODO
347 348
                    // TODO does the limited range of valid years cause years to
                    // start/end part way through? that would affect range
S
sherman 已提交
349
                }
S
sherman 已提交
350
                return getChronology().range(f);
S
sherman 已提交
351
            }
352
            throw new UnsupportedTemporalTypeException("Unsupported field: " + field.getName());
S
sherman 已提交
353
        }
S
sherman 已提交
354 355 356
        return field.rangeRefinedBy(this);
    }

S
sherman 已提交
357 358 359 360
    @Override
    public long getLong(TemporalField field) {
        if (field instanceof ChronoField) {
            switch ((ChronoField) field) {
361 362 363
                case DAY_OF_WEEK: return getDayOfWeek();
                case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((getDayOfWeek() - 1) % 7) + 1;
                case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((getDayOfYear() - 1) % 7) + 1;
S
sherman 已提交
364
                case DAY_OF_MONTH: return this.dayOfMonth;
365
                case DAY_OF_YEAR: return this.getDayOfYear();
S
sherman 已提交
366 367
                case EPOCH_DAY: return toEpochDay();
                case ALIGNED_WEEK_OF_MONTH: return ((dayOfMonth - 1) / 7) + 1;
368
                case ALIGNED_WEEK_OF_YEAR: return ((getDayOfYear() - 1) / 7) + 1;
S
sherman 已提交
369
                case MONTH_OF_YEAR: return monthOfYear;
370 371 372 373
                case PROLEPTIC_MONTH: return getProlepticMonth();
                case YEAR_OF_ERA: return prolepticYear;
                case YEAR: return prolepticYear;
                case ERA: return getEraValue();
S
sherman 已提交
374
            }
375
            throw new UnsupportedTemporalTypeException("Unsupported field: " + field.getName());
S
sherman 已提交
376
        }
S
sherman 已提交
377
        return field.getFrom(this);
S
sherman 已提交
378 379
    }

380 381 382 383
    private long getProlepticMonth() {
        return prolepticYear * 12L + monthOfYear - 1;
    }

S
sherman 已提交
384 385 386 387
    @Override
    public HijrahDate with(TemporalField field, long newValue) {
        if (field instanceof ChronoField) {
            ChronoField f = (ChronoField) field;
388 389
            // not using checkValidIntValue so EPOCH_DAY and PROLEPTIC_MONTH work
            chrono.range(f).checkValidValue(newValue, f);    // TODO: validate value
S
sherman 已提交
390 391
            int nvalue = (int) newValue;
            switch (f) {
392
                case DAY_OF_WEEK: return plusDays(newValue - getDayOfWeek());
S
sherman 已提交
393 394
                case ALIGNED_DAY_OF_WEEK_IN_MONTH: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));
                case ALIGNED_DAY_OF_WEEK_IN_YEAR: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));
395 396 397
                case DAY_OF_MONTH: return resolvePreviousValid(prolepticYear, monthOfYear, nvalue);
                case DAY_OF_YEAR: return resolvePreviousValid(prolepticYear, ((nvalue - 1) / 30) + 1, ((nvalue - 1) % 30) + 1);
                case EPOCH_DAY: return new HijrahDate(chrono, newValue);
S
sherman 已提交
398 399
                case ALIGNED_WEEK_OF_MONTH: return plusDays((newValue - getLong(ALIGNED_WEEK_OF_MONTH)) * 7);
                case ALIGNED_WEEK_OF_YEAR: return plusDays((newValue - getLong(ALIGNED_WEEK_OF_YEAR)) * 7);
400 401 402
                case MONTH_OF_YEAR: return resolvePreviousValid(prolepticYear, nvalue, dayOfMonth);
                case PROLEPTIC_MONTH: return plusMonths(newValue - getProlepticMonth());
                case YEAR_OF_ERA: return resolvePreviousValid(prolepticYear >= 1 ? nvalue : 1 - nvalue, monthOfYear, dayOfMonth);
S
sherman 已提交
403
                case YEAR: return resolvePreviousValid(nvalue, monthOfYear, dayOfMonth);
404
                case ERA: return resolvePreviousValid(1 - prolepticYear, monthOfYear, dayOfMonth);
S
sherman 已提交
405
            }
406
            throw new UnsupportedTemporalTypeException("Unsupported field: " + field.getName());
S
sherman 已提交
407
        }
408
        return ChronoLocalDate.super.with(field, newValue);
S
sherman 已提交
409 410
    }

411 412
    private HijrahDate resolvePreviousValid(int prolepticYear, int month, int day) {
        int monthDays = chrono.getMonthLength(prolepticYear, month);
S
sherman 已提交
413 414 415
        if (day > monthDays) {
            day = monthDays;
        }
416
        return HijrahDate.of(chrono, prolepticYear, month, day);
S
sherman 已提交
417 418
    }

S
sherman 已提交
419 420
    /**
     * {@inheritDoc}
421 422
     * @throws DateTimeException if unable to make the adjustment.
     *     For example, if the adjuster requires an ISO chronology
S
sherman 已提交
423 424
     * @throws ArithmeticException {@inheritDoc}
     */
S
sherman 已提交
425
    @Override
S
sherman 已提交
426
    public  HijrahDate with(TemporalAdjuster adjuster) {
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
        return super.with(adjuster);
    }

    /**
     * Returns a {@code HijrahDate} with the Chronology requested.
     * <p>
     * The year, month, and day are checked against the new requested
     * HijrahChronology.  If the chronology has a shorter month length
     * for the month, the day is reduced to be the last day of the month.
     *
     * @param chronology the new HijrahChonology, non-null
     * @return a HijrahDate with the requested HijrahChronology, non-null
     */
    public HijrahDate withVariant(HijrahChronology chronology) {
        if (chrono == chronology) {
            return this;
        }
        // Like resolvePreviousValid the day is constrained to stay in the same month
        int monthDays = chronology.getDayOfYear(prolepticYear, monthOfYear);
        return HijrahDate.of(chronology, prolepticYear, monthOfYear,(dayOfMonth > monthDays) ? monthDays : dayOfMonth );
S
sherman 已提交
447 448
    }

S
sherman 已提交
449 450 451 452 453 454 455
    /**
     * {@inheritDoc}
     * @throws DateTimeException {@inheritDoc}
     * @throws ArithmeticException {@inheritDoc}
     */
    @Override
    public HijrahDate plus(TemporalAmount amount) {
456
        return super.plus(amount);
S
sherman 已提交
457 458 459 460 461 462 463
    }

    /**
     * {@inheritDoc}
     * @throws DateTimeException {@inheritDoc}
     * @throws ArithmeticException {@inheritDoc}
     */
S
sherman 已提交
464
    @Override
S
sherman 已提交
465
    public HijrahDate minus(TemporalAmount amount) {
466
        return super.minus(amount);
S
sherman 已提交
467 468 469 470
    }

    @Override
    public long toEpochDay() {
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
        return chrono.getEpochDay(prolepticYear, monthOfYear, dayOfMonth);
    }

    /**
     * Gets the day-of-year field.
     * <p>
     * This method returns the primitive {@code int} value for the day-of-year.
     *
     * @return the day-of-year
     */
    private int getDayOfYear() {
        return chrono.getDayOfYear(prolepticYear, monthOfYear);
    }

    /**
     * Gets the day-of-week value.
     *
     * @return the day-of-week; computed from the epochday
     */
    private int getDayOfWeek() {
        int dow0 = (int)Math.floorMod(toEpochDay() + 3, 7);
        return dow0 + 1;
    }

    /**
     * Gets the Era of this date.
     *
     * @return the Era of this date; computed from epochDay
     */
    private int getEraValue() {
        return (prolepticYear > 1 ? 1 : 0);
S
sherman 已提交
502 503 504 505 506 507 508 509 510 511
    }

    //-----------------------------------------------------------------------
    /**
     * Checks if the year is a leap year, according to the Hijrah calendar system rules.
     *
     * @return true if this date is in a leap year
     */
    @Override
    public boolean isLeapYear() {
512
        return chrono.isLeapYear(prolepticYear);
S
sherman 已提交
513 514 515 516
    }

    //-----------------------------------------------------------------------
    @Override
S
sherman 已提交
517
    HijrahDate plusYears(long years) {
S
sherman 已提交
518 519 520
        if (years == 0) {
            return this;
        }
521 522
        int newYear = Math.addExact(this.prolepticYear, (int)years);
        return resolvePreviousValid(newYear, monthOfYear, dayOfMonth);
S
sherman 已提交
523 524 525
    }

    @Override
526 527
    HijrahDate plusMonths(long monthsToAdd) {
        if (monthsToAdd == 0) {
S
sherman 已提交
528 529
            return this;
        }
530 531 532 533 534
        long monthCount = prolepticYear * 12L + (monthOfYear - 1);
        long calcMonths = monthCount + monthsToAdd;  // safe overflow
        int newYear = chrono.checkValidYear(Math.floorDiv(calcMonths, 12L));
        int newMonth = (int)Math.floorMod(calcMonths, 12L) + 1;
        return resolvePreviousValid(newYear, newMonth, dayOfMonth);
S
sherman 已提交
535 536 537
    }

    @Override
S
sherman 已提交
538
    HijrahDate plusWeeks(long weeksToAdd) {
539
        return super.plusWeeks(weeksToAdd);
S
sherman 已提交
540 541 542 543
    }

    @Override
    HijrahDate plusDays(long days) {
544
        return new HijrahDate(chrono, toEpochDay() + days);
S
sherman 已提交
545 546
    }

S
sherman 已提交
547 548
    @Override
    public HijrahDate plus(long amountToAdd, TemporalUnit unit) {
549
        return super.plus(amountToAdd, unit);
S
sherman 已提交
550 551 552 553
    }

    @Override
    public HijrahDate minus(long amountToSubtract, TemporalUnit unit) {
554
        return super.minus(amountToSubtract, unit);
S
sherman 已提交
555 556 557 558
    }

    @Override
    HijrahDate minusYears(long yearsToSubtract) {
559
        return super.minusYears(yearsToSubtract);
S
sherman 已提交
560 561 562 563
    }

    @Override
    HijrahDate minusMonths(long monthsToSubtract) {
564
        return super.minusMonths(monthsToSubtract);
S
sherman 已提交
565 566 567 568
    }

    @Override
    HijrahDate minusWeeks(long weeksToSubtract) {
569
        return super.minusWeeks(weeksToSubtract);
S
sherman 已提交
570 571 572 573
    }

    @Override
    HijrahDate minusDays(long daysToSubtract) {
574
        return super.minusDays(daysToSubtract);
S
sherman 已提交
575 576
    }

S
sherman 已提交
577 578
    @Override        // for javadoc and covariant return type
    public final ChronoLocalDateTime<HijrahDate> atTime(LocalTime localTime) {
579
        return super.atTime(localTime);
S
sherman 已提交
580 581 582 583 584
    }

    @Override
    public Period periodUntil(ChronoLocalDate<?> endDate) {
        // TODO: untested
585 586
        HijrahDate end = getChronology().date(endDate);
        long totalMonths = (end.prolepticYear - this.prolepticYear) * 12 + (end.monthOfYear - this.monthOfYear);  // safe
S
sherman 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600
        int days = end.dayOfMonth - this.dayOfMonth;
        if (totalMonths > 0 && days < 0) {
            totalMonths--;
            HijrahDate calcDate = this.plusMonths(totalMonths);
            days = (int) (end.toEpochDay() - calcDate.toEpochDay());  // safe
        } else if (totalMonths < 0 && days > 0) {
            totalMonths++;
            days -= end.lengthOfMonth();
        }
        long years = totalMonths / 12;  // safe
        int months = (int) (totalMonths % 12);  // safe
        return Period.of(Math.toIntExact(years), months, days);
    }

S
sherman 已提交
601 602 603 604 605 606
    //-----------------------------------------------------------------------
    private Object writeReplace() {
        return new Ser(Ser.HIJRAH_DATE_TYPE, this);
    }

    void writeExternal(ObjectOutput out) throws IOException {
S
sherman 已提交
607
        // HijrahChronology is implicit in the Hijrah_DATE_TYPE
S
sherman 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
        out.writeObject(chrono);
        out.writeInt(get(YEAR));
        out.writeByte(get(MONTH_OF_YEAR));
        out.writeByte(get(DAY_OF_MONTH));
    }

    /**
     * Replaces the date instance from the stream with a valid one.
     * ReadExternal has already read the fields and created a new instance
     * from the data.
     *
     * @return the resolved date, never null
     */
    private Object readResolve() {
        return this;
    }

S
sherman 已提交
625
    static ChronoLocalDate<HijrahDate> readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
626
        HijrahChronology chrono = (HijrahChronology) in.readObject();
S
sherman 已提交
627 628 629 630 631 632 633
        int year = in.readInt();
        int month = in.readByte();
        int dayOfMonth = in.readByte();
        return chrono.date(year, month, dayOfMonth);
    }

}