src/share/classes/java/time/MonthDay.java

Print this page




  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time.temporal;
  63 
  64 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
  65 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  66 
  67 import java.io.DataInput;
  68 import java.io.DataOutput;
  69 import java.io.IOException;
  70 import java.io.InvalidObjectException;
  71 import java.io.ObjectStreamException;
  72 import java.io.Serializable;
  73 import java.time.Clock;
  74 import java.time.DateTimeException;
  75 import java.time.LocalDate;
  76 import java.time.Month;
  77 import java.time.ZoneId;
  78 import java.time.format.DateTimeFormatter;
  79 import java.time.format.DateTimeFormatterBuilder;
  80 import java.time.format.DateTimeParseException;








  81 import java.util.Objects;
  82 
  83 /**
  84  * A month-day in the ISO-8601 calendar system, such as {@code --12-03}.
  85  * <p>
  86  * {@code MonthDay} is an immutable date-time object that represents the combination
  87  * of a year and month. Any field that can be derived from a month and day, such as
  88  * quarter-of-year, can be obtained.
  89  * <p>
  90  * This class does not store or represent a year, time or time-zone.
  91  * For example, the value "December 3rd" can be stored in a {@code MonthDay}.
  92  * <p>
  93  * Since a {@code MonthDay} does not possess a year, the leap day of
  94  * February 29th is considered valid.
  95  * <p>
  96  * This class implements {@link TemporalAccessor} rather than {@link Temporal}.
  97  * This is because it is not possible to define whether February 29th is valid or not
  98  * without external information, preventing the implementation of plus/minus.
  99  * Related to this, {@code MonthDay} only provides access to query and set the fields
 100  * {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH}.


 181      */
 182     public static MonthDay now(Clock clock) {
 183         final LocalDate now = LocalDate.now(clock);  // called once
 184         return MonthDay.of(now.getMonth(), now.getDayOfMonth());
 185     }
 186 
 187     //-----------------------------------------------------------------------
 188     /**
 189      * Obtains an instance of {@code MonthDay}.
 190      * <p>
 191      * The day-of-month must be valid for the month within a leap year.
 192      * Hence, for February, day 29 is valid.
 193      * <p>
 194      * For example, passing in April and day 31 will throw an exception, as
 195      * there can never be April 31st in any year. By contrast, passing in
 196      * February 29th is permitted, as that month-day can sometimes be valid.
 197      *
 198      * @param month  the month-of-year to represent, not null
 199      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 200      * @return the month-day, not null
 201      * @throws DateTimeException if the value of any field is out of range
 202      * @throws DateTimeException if the day-of-month is invalid for the month
 203      */
 204     public static MonthDay of(Month month, int dayOfMonth) {
 205         Objects.requireNonNull(month, "month");
 206         DAY_OF_MONTH.checkValidValue(dayOfMonth);
 207         if (dayOfMonth > month.maxLength()) {
 208             throw new DateTimeException("Illegal value for DayOfMonth field, value " + dayOfMonth +
 209                     " is not valid for month " + month.name());
 210         }
 211         return new MonthDay(month.getValue(), dayOfMonth);
 212     }
 213 
 214     /**
 215      * Obtains an instance of {@code MonthDay}.
 216      * <p>
 217      * The day-of-month must be valid for the month within a leap year.
 218      * Hence, for month 2 (February), day 29 is valid.
 219      * <p>
 220      * For example, passing in month 4 (April) and day 31 will throw an exception, as
 221      * there can never be April 31st in any year. By contrast, passing in
 222      * February 29th is permitted, as that month-day can sometimes be valid.
 223      *
 224      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
 225      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 226      * @return the month-day, not null
 227      * @throws DateTimeException if the value of any field is out of range
 228      * @throws DateTimeException if the day-of-month is invalid for the month
 229      */
 230     public static MonthDay of(int month, int dayOfMonth) {
 231         return of(Month.of(month), dayOfMonth);
 232     }
 233 
 234     //-----------------------------------------------------------------------
 235     /**
 236      * Obtains an instance of {@code MonthDay} from a temporal object.
 237      * <p>
 238      * A {@code TemporalAccessor} represents some form of date and time information.
 239      * This factory converts the arbitrary temporal object to an instance of {@code MonthDay}.

 240      * <p>
 241      * The conversion extracts the {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and
 242      * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} fields.
 243      * The extraction is only permitted if the date-time has an ISO chronology.
 244      * <p>
 245      * This method matches the signature of the functional interface {@link TemporalQuery}
 246      * allowing it to be used in queries via method reference, {@code MonthDay::from}.
 247      *
 248      * @param temporal  the temporal object to convert, not null
 249      * @return the month-day, not null
 250      * @throws DateTimeException if unable to convert to a {@code MonthDay}
 251      */
 252     public static MonthDay from(TemporalAccessor temporal) {
 253         if (temporal instanceof MonthDay) {
 254             return (MonthDay) temporal;
 255         }
 256         try {
 257             if (ISOChrono.INSTANCE.equals(Chrono.from(temporal)) == false) {
 258                 temporal = LocalDate.from(temporal);
 259             }
 260             return of(temporal.get(MONTH_OF_YEAR), temporal.get(DAY_OF_MONTH));
 261         } catch (DateTimeException ex) {
 262             throw new DateTimeException("Unable to obtain MonthDay from TemporalAccessor: " + temporal.getClass(), ex);
 263         }
 264     }
 265 
 266     //-----------------------------------------------------------------------
 267     /**
 268      * Obtains an instance of {@code MonthDay} from a text string such as {@code --12-03}.
 269      * <p>
 270      * The string must represent a valid month-day.
 271      * The format is {@code --MM-dd}.
 272      *
 273      * @param text  the text to parse such as "--12-03", not null
 274      * @return the parsed month-day, not null
 275      * @throws DateTimeParseException if the text cannot be parsed
 276      */
 277     public static MonthDay parse(CharSequence text) {


 297     /**
 298      * Constructor, previously validated.
 299      *
 300      * @param month  the month-of-year to represent, validated from 1 to 12
 301      * @param dayOfMonth  the day-of-month to represent, validated from 1 to 29-31
 302      */
 303     private MonthDay(int month, int dayOfMonth) {
 304         this.month = month;
 305         this.day = dayOfMonth;
 306     }
 307 
 308     //-----------------------------------------------------------------------
 309     /**
 310      * Checks if the specified field is supported.
 311      * <p>
 312      * This checks if this month-day can be queried for the specified field.
 313      * If false, then calling the {@link #range(TemporalField) range} and
 314      * {@link #get(TemporalField) get} methods will throw an exception.
 315      * <p>
 316      * If the field is a {@link ChronoField} then the query is implemented here.
 317      * The {@link #isSupported(TemporalField) supported fields} will return valid
 318      * values based on this date-time.
 319      * The supported fields are:
 320      * <ul>
 321      * <li>{@code MONTH_OF_YEAR}
 322      * <li>{@code YEAR}
 323      * </ul>
 324      * All other {@code ChronoField} instances will return false.
 325      * <p>
 326      * If the field is not a {@code ChronoField}, then the result of this method
 327      * is obtained by invoking {@code TemporalField.doIsSupported(TemporalAccessor)}
 328      * passing {@code this} as the argument.
 329      * Whether the field is supported is determined by the field.
 330      *
 331      * @param field  the field to check, null returns false
 332      * @return true if the field is supported on this month-day, false if not
 333      */
 334     @Override
 335     public boolean isSupported(TemporalField field) {
 336         if (field instanceof ChronoField) {
 337             return field == MONTH_OF_YEAR || field == DAY_OF_MONTH;
 338         }
 339         return field != null && field.doIsSupported(this);
 340     }
 341 
 342     /**
 343      * Gets the range of valid values for the specified field.
 344      * <p>
 345      * The range object expresses the minimum and maximum valid values for a field.
 346      * This month-day is used to enhance the accuracy of the returned range.
 347      * If it is not possible to return the range, because the field is not supported
 348      * or for some other reason, an exception is thrown.
 349      * <p>
 350      * If the field is a {@link ChronoField} then the query is implemented here.
 351      * The {@link #isSupported(TemporalField) supported fields} will return
 352      * appropriate range instances.
 353      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 354      * <p>
 355      * If the field is not a {@code ChronoField}, then the result of this method
 356      * is obtained by invoking {@code TemporalField.doRange(TemporalAccessor)}
 357      * passing {@code this} as the argument.
 358      * Whether the range can be obtained is determined by the field.
 359      *
 360      * @param field  the field to query the range for, not null
 361      * @return the range of valid values for the field, not null
 362      * @throws DateTimeException if the range for the field cannot be obtained
 363      */
 364     @Override
 365     public ValueRange range(TemporalField field) {
 366         if (field == MONTH_OF_YEAR) {
 367             return field.range();
 368         } else if (field == DAY_OF_MONTH) {
 369             return ValueRange.of(1, getMonth().minLength(), getMonth().maxLength());
 370         }
 371         return TemporalAccessor.super.range(field);
 372     }
 373 
 374     /**
 375      * Gets the value of the specified field from this month-day as an {@code int}.
 376      * <p>
 377      * This queries this month-day for the value for the specified field.
 378      * The returned value will always be within the valid range of values for the field.
 379      * If it is not possible to return the value, because the field is not supported
 380      * or for some other reason, an exception is thrown.
 381      * <p>
 382      * If the field is a {@link ChronoField} then the query is implemented here.
 383      * The {@link #isSupported(TemporalField) supported fields} will return valid
 384      * values based on this month-day.
 385      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 386      * <p>
 387      * If the field is not a {@code ChronoField}, then the result of this method
 388      * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)}
 389      * passing {@code this} as the argument. Whether the value can be obtained,
 390      * and what the value represents, is determined by the field.
 391      *
 392      * @param field  the field to get, not null
 393      * @return the value for the field
 394      * @throws DateTimeException if a value for the field cannot be obtained
 395      * @throws ArithmeticException if numeric overflow occurs
 396      */
 397     @Override  // override for Javadoc
 398     public int get(TemporalField field) {
 399         return range(field).checkValidIntValue(getLong(field), field);
 400     }
 401 
 402     /**
 403      * Gets the value of the specified field from this month-day as a {@code long}.
 404      * <p>
 405      * This queries this month-day for the value for the specified field.
 406      * If it is not possible to return the value, because the field is not supported
 407      * or for some other reason, an exception is thrown.
 408      * <p>
 409      * If the field is a {@link ChronoField} then the query is implemented here.
 410      * The {@link #isSupported(TemporalField) supported fields} will return valid
 411      * values based on this month-day.
 412      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 413      * <p>
 414      * If the field is not a {@code ChronoField}, then the result of this method
 415      * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)}
 416      * passing {@code this} as the argument. Whether the value can be obtained,
 417      * and what the value represents, is determined by the field.
 418      *
 419      * @param field  the field to get, not null
 420      * @return the value for the field
 421      * @throws DateTimeException if a value for the field cannot be obtained
 422      * @throws ArithmeticException if numeric overflow occurs
 423      */
 424     @Override
 425     public long getLong(TemporalField field) {
 426         if (field instanceof ChronoField) {
 427             switch ((ChronoField) field) {
 428                 // alignedDOW and alignedWOM not supported because they cannot be set in with()
 429                 case DAY_OF_MONTH: return day;
 430                 case MONTH_OF_YEAR: return month;
 431             }
 432             throw new DateTimeException("Unsupported field: " + field.getName());
 433         }
 434         return field.doGet(this);
 435     }
 436 
 437     //-----------------------------------------------------------------------
 438     /**














 439      * Gets the month-of-year field using the {@code Month} enum.
 440      * <p>
 441      * This method returns the enum {@link Month} for the month.
 442      * This avoids confusion as to what {@code int} values mean.
 443      * If you need access to the primitive {@code int} value then the enum
 444      * provides the {@link Month#getValue() int value}.
 445      *
 446      * @return the month-of-year, not null

 447      */
 448     public Month getMonth() {
 449         return Month.of(month);
 450     }
 451 
 452     /**
 453      * Gets the day-of-month field.
 454      * <p>
 455      * This method returns the primitive {@code int} value for the day-of-month.
 456      *
 457      * @return the day-of-month, from 1 to 31
 458      */
 459     public int getDayOfMonth() {
 460         return day;
 461     }
 462 
 463     //-----------------------------------------------------------------------
 464     /**
 465      * Checks if the year is valid for this month-day.
 466      * <p>


 507      */
 508     public MonthDay with(Month month) {
 509         Objects.requireNonNull(month, "month");
 510         if (month.getValue() == this.month) {
 511             return this;
 512         }
 513         int day = Math.min(this.day, month.maxLength());
 514         return new MonthDay(month.getValue(), day);
 515     }
 516 
 517     /**
 518      * Returns a copy of this {@code MonthDay} with the day-of-month altered.
 519      * <p>
 520      * This returns a month-day with the specified day-of-month.
 521      * If the day-of-month is invalid for the month, an exception is thrown.
 522      * <p>
 523      * This instance is immutable and unaffected by this method call.
 524      *
 525      * @param dayOfMonth  the day-of-month to set in the return month-day, from 1 to 31
 526      * @return a {@code MonthDay} based on this month-day with the requested day, not null
 527      * @throws DateTimeException if the day-of-month value is invalid
 528      * @throws DateTimeException if the day-of-month is invalid for the month
 529      */
 530     public MonthDay withDayOfMonth(int dayOfMonth) {
 531         if (dayOfMonth == this.day) {
 532             return this;
 533         }
 534         return of(month, dayOfMonth);
 535     }
 536 
 537     //-----------------------------------------------------------------------
 538     /**
 539      * Queries this month-day using the specified query.
 540      * <p>
 541      * This queries this month-day using the specified query strategy object.
 542      * The {@code TemporalQuery} object defines the logic to be used to
 543      * obtain the result. Read the documentation of the query to understand
 544      * what the result of this method will be.
 545      * <p>
 546      * The result of this method is obtained by invoking the
 547      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
 548      * specified query passing {@code this} as the argument.
 549      *
 550      * @param <R> the type of the result
 551      * @param query  the query to invoke, not null
 552      * @return the query result, null may be returned (defined by the query)
 553      * @throws DateTimeException if unable to query (defined by the query)
 554      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
 555      */
 556     @SuppressWarnings("unchecked")
 557     @Override
 558     public <R> R query(TemporalQuery<R> query) {
 559         if (query == Queries.chrono()) {
 560             return (R) ISOChrono.INSTANCE;
 561         }
 562         return TemporalAccessor.super.query(query);
 563     }
 564 
 565     /**
 566      * Adjusts the specified temporal object to have this month-day.
 567      * <p>
 568      * This returns a temporal object of the same observable type as the input
 569      * with the month and day-of-month changed to be the same as this.
 570      * <p>
 571      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
 572      * twice, passing {@link ChronoField#MONTH_OF_YEAR} and
 573      * {@link ChronoField#DAY_OF_MONTH} as the fields.
 574      * If the specified temporal object does not use the ISO calendar system then
 575      * a {@code DateTimeException} is thrown.
 576      * <p>
 577      * In most cases, it is clearer to reverse the calling pattern by using
 578      * {@link Temporal#with(TemporalAdjuster)}:
 579      * <pre>
 580      *   // these two lines are equivalent, but the second approach is recommended
 581      *   temporal = thisMonthDay.adjustInto(temporal);
 582      *   temporal = temporal.with(thisMonthDay);
 583      * </pre>
 584      * <p>
 585      * This instance is immutable and unaffected by this method call.
 586      *
 587      * @param temporal  the target object to be adjusted, not null
 588      * @return the adjusted object, not null
 589      * @throws DateTimeException if unable to make the adjustment
 590      * @throws ArithmeticException if numeric overflow occurs
 591      */
 592     @Override
 593     public Temporal adjustInto(Temporal temporal) {
 594         if (Chrono.from(temporal).equals(ISOChrono.INSTANCE) == false) {
 595             throw new DateTimeException("Adjustment only supported on ISO date-time");
 596         }
 597         temporal = temporal.with(MONTH_OF_YEAR, month);
 598         return temporal.with(DAY_OF_MONTH, Math.min(temporal.range(DAY_OF_MONTH).getMaximum(), day));
 599     }
 600 
 601     //-----------------------------------------------------------------------
 602     /**
 603      * Returns a date formed from this month-day at the specified year.


 604      * <p>
 605      * This combines this month-day and the specified year to form a {@code LocalDate}.
 606      * A month-day of February 29th will be adjusted to February 28th in the resulting
 607      * date if the year is not a leap year.
 608      * <p>
 609      * This instance is immutable and unaffected by this method call.
 610      *
 611      * @param year  the year to use, from MIN_YEAR to MAX_YEAR
 612      * @return the local date formed from this month-day and the specified year, not null
 613      * @see Year#atMonthDay(MonthDay)
 614      */
 615     public LocalDate atYear(int year) {
 616         return LocalDate.of(year, month, isValidYear(year) ? day : 28);
 617     }
 618 
 619     //-----------------------------------------------------------------------
 620     /**
 621      * Compares this month-day to another month-day.
 622      * <p>
 623      * The comparison is based first on value of the month, then on the value of the day.
 624      * It is "consistent with equals", as defined by {@link Comparable}.
 625      *
 626      * @param other  the other month-day to compare to, not null
 627      * @return the comparator value, negative if less, positive if greater
 628      */

 629     public int compareTo(MonthDay other) {
 630         int cmp = (month - other.month);
 631         if (cmp == 0) {
 632             cmp = (day - other.day);
 633         }
 634         return cmp;
 635     }
 636 
 637     /**
 638      * Is this month-day after the specified month-day.
 639      *
 640      * @param other  the other month-day to compare to, not null
 641      * @return true if this is after the specified month-day
 642      */
 643     public boolean isAfter(MonthDay other) {
 644         return compareTo(other) > 0;
 645     }
 646 
 647     /**
 648      * Is this month-day before the specified month-day.


 688     //-----------------------------------------------------------------------
 689     /**
 690      * Outputs this month-day as a {@code String}, such as {@code --12-03}.
 691      * <p>
 692      * The output will be in the format {@code --MM-dd}:
 693      *
 694      * @return a string representation of this month-day, not null
 695      */
 696     @Override
 697     public String toString() {
 698         return new StringBuilder(10).append("--")
 699             .append(month < 10 ? "0" : "").append(month)
 700             .append(day < 10 ? "-0" : "-").append(day)
 701             .toString();
 702     }
 703 
 704     /**
 705      * Outputs this month-day as a {@code String} using the formatter.
 706      * <p>
 707      * This month-day will be passed to the formatter
 708      * {@link DateTimeFormatter#print(TemporalAccessor) print method}.
 709      *
 710      * @param formatter  the formatter to use, not null
 711      * @return the formatted month-day string, not null
 712      * @throws DateTimeException if an error occurs during printing
 713      */
 714     public String toString(DateTimeFormatter formatter) {
 715         Objects.requireNonNull(formatter, "formatter");
 716         return formatter.print(this);
 717     }
 718 
 719     //-----------------------------------------------------------------------
 720     /**
 721      * Writes the object using a
 722      * <a href="../../../serialized-form.html#java.time.temporal.Ser">dedicated serialized form</a>.
 723      * <pre>
 724      *  out.writeByte(6);  // identifies this as a Year
 725      *  out.writeByte(month);
 726      *  out.writeByte(day);
 727      * </pre>
 728      *
 729      * @return the instance of {@code Ser}, not null
 730      */
 731     private Object writeReplace() {
 732         return new Ser(Ser.MONTH_DAY_TYPE, this);
 733     }
 734 
 735     /**
 736      * Defend against malicious streams.
 737      * @return never
 738      * @throws InvalidObjectException always
 739      */
 740     private Object readResolve() throws ObjectStreamException {
 741         throw new InvalidObjectException("Deserialization via serialization delegate");
 742     }
 743 
 744     void writeExternal(DataOutput out) throws IOException {


  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time;
  63 
  64 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
  65 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  66 
  67 import java.io.DataInput;
  68 import java.io.DataOutput;
  69 import java.io.IOException;
  70 import java.io.InvalidObjectException;
  71 import java.io.ObjectStreamException;
  72 import java.io.Serializable;
  73 import java.time.chrono.Chronology;
  74 import java.time.chrono.IsoChronology;



  75 import java.time.format.DateTimeFormatter;
  76 import java.time.format.DateTimeFormatterBuilder;
  77 import java.time.format.DateTimeParseException;
  78 import java.time.temporal.ChronoField;
  79 import java.time.temporal.Queries;
  80 import java.time.temporal.Temporal;
  81 import java.time.temporal.TemporalAccessor;
  82 import java.time.temporal.TemporalAdjuster;
  83 import java.time.temporal.TemporalField;
  84 import java.time.temporal.TemporalQuery;
  85 import java.time.temporal.ValueRange;
  86 import java.util.Objects;
  87 
  88 /**
  89  * A month-day in the ISO-8601 calendar system, such as {@code --12-03}.
  90  * <p>
  91  * {@code MonthDay} is an immutable date-time object that represents the combination
  92  * of a year and month. Any field that can be derived from a month and day, such as
  93  * quarter-of-year, can be obtained.
  94  * <p>
  95  * This class does not store or represent a year, time or time-zone.
  96  * For example, the value "December 3rd" can be stored in a {@code MonthDay}.
  97  * <p>
  98  * Since a {@code MonthDay} does not possess a year, the leap day of
  99  * February 29th is considered valid.
 100  * <p>
 101  * This class implements {@link TemporalAccessor} rather than {@link Temporal}.
 102  * This is because it is not possible to define whether February 29th is valid or not
 103  * without external information, preventing the implementation of plus/minus.
 104  * Related to this, {@code MonthDay} only provides access to query and set the fields
 105  * {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH}.


 186      */
 187     public static MonthDay now(Clock clock) {
 188         final LocalDate now = LocalDate.now(clock);  // called once
 189         return MonthDay.of(now.getMonth(), now.getDayOfMonth());
 190     }
 191 
 192     //-----------------------------------------------------------------------
 193     /**
 194      * Obtains an instance of {@code MonthDay}.
 195      * <p>
 196      * The day-of-month must be valid for the month within a leap year.
 197      * Hence, for February, day 29 is valid.
 198      * <p>
 199      * For example, passing in April and day 31 will throw an exception, as
 200      * there can never be April 31st in any year. By contrast, passing in
 201      * February 29th is permitted, as that month-day can sometimes be valid.
 202      *
 203      * @param month  the month-of-year to represent, not null
 204      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 205      * @return the month-day, not null
 206      * @throws DateTimeException if the value of any field is out of range,
 207      *  or if the day-of-month is invalid for the month
 208      */
 209     public static MonthDay of(Month month, int dayOfMonth) {
 210         Objects.requireNonNull(month, "month");
 211         DAY_OF_MONTH.checkValidValue(dayOfMonth);
 212         if (dayOfMonth > month.maxLength()) {
 213             throw new DateTimeException("Illegal value for DayOfMonth field, value " + dayOfMonth +
 214                     " is not valid for month " + month.name());
 215         }
 216         return new MonthDay(month.getValue(), dayOfMonth);
 217     }
 218 
 219     /**
 220      * Obtains an instance of {@code MonthDay}.
 221      * <p>
 222      * The day-of-month must be valid for the month within a leap year.
 223      * Hence, for month 2 (February), day 29 is valid.
 224      * <p>
 225      * For example, passing in month 4 (April) and day 31 will throw an exception, as
 226      * there can never be April 31st in any year. By contrast, passing in
 227      * February 29th is permitted, as that month-day can sometimes be valid.
 228      *
 229      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
 230      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 231      * @return the month-day, not null
 232      * @throws DateTimeException if the value of any field is out of range,
 233      *  or if the day-of-month is invalid for the month
 234      */
 235     public static MonthDay of(int month, int dayOfMonth) {
 236         return of(Month.of(month), dayOfMonth);
 237     }
 238 
 239     //-----------------------------------------------------------------------
 240     /**
 241      * Obtains an instance of {@code MonthDay} from a temporal object.
 242      * <p>
 243      * This obtains a month-day 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 MonthDay}.
 246      * <p>
 247      * The conversion extracts the {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and
 248      * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} fields.
 249      * The extraction is only permitted if the date-time has an ISO chronology.
 250      * <p>
 251      * This method matches the signature of the functional interface {@link TemporalQuery}
 252      * allowing it to be used in queries via method reference, {@code MonthDay::from}.
 253      *
 254      * @param temporal  the temporal object to convert, not null
 255      * @return the month-day, not null
 256      * @throws DateTimeException if unable to convert to a {@code MonthDay}
 257      */
 258     public static MonthDay from(TemporalAccessor temporal) {
 259         if (temporal instanceof MonthDay) {
 260             return (MonthDay) temporal;
 261         }
 262         try {
 263             if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
 264                 temporal = LocalDate.from(temporal);
 265             }
 266             return of(temporal.get(MONTH_OF_YEAR), temporal.get(DAY_OF_MONTH));
 267         } catch (DateTimeException ex) {
 268             throw new DateTimeException("Unable to obtain MonthDay from TemporalAccessor: " + temporal.getClass(), ex);
 269         }
 270     }
 271 
 272     //-----------------------------------------------------------------------
 273     /**
 274      * Obtains an instance of {@code MonthDay} from a text string such as {@code --12-03}.
 275      * <p>
 276      * The string must represent a valid month-day.
 277      * The format is {@code --MM-dd}.
 278      *
 279      * @param text  the text to parse such as "--12-03", not null
 280      * @return the parsed month-day, not null
 281      * @throws DateTimeParseException if the text cannot be parsed
 282      */
 283     public static MonthDay parse(CharSequence text) {


 303     /**
 304      * Constructor, previously validated.
 305      *
 306      * @param month  the month-of-year to represent, validated from 1 to 12
 307      * @param dayOfMonth  the day-of-month to represent, validated from 1 to 29-31
 308      */
 309     private MonthDay(int month, int dayOfMonth) {
 310         this.month = month;
 311         this.day = dayOfMonth;
 312     }
 313 
 314     //-----------------------------------------------------------------------
 315     /**
 316      * Checks if the specified field is supported.
 317      * <p>
 318      * This checks if this month-day can be queried for the specified field.
 319      * If false, then calling the {@link #range(TemporalField) range} and
 320      * {@link #get(TemporalField) get} methods will throw an exception.
 321      * <p>
 322      * If the field is a {@link ChronoField} then the query is implemented here.


 323      * The supported fields are:
 324      * <ul>
 325      * <li>{@code MONTH_OF_YEAR}
 326      * <li>{@code YEAR}
 327      * </ul>
 328      * All other {@code ChronoField} instances will return false.
 329      * <p>
 330      * If the field is not a {@code ChronoField}, then the result of this method
 331      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
 332      * passing {@code this} as the argument.
 333      * Whether the field is supported is determined by the field.
 334      *
 335      * @param field  the field to check, null returns false
 336      * @return true if the field is supported on this month-day, false if not
 337      */
 338     @Override
 339     public boolean isSupported(TemporalField field) {
 340         if (field instanceof ChronoField) {
 341             return field == MONTH_OF_YEAR || field == DAY_OF_MONTH;
 342         }
 343         return field != null && field.isSupportedBy(this);
 344     }
 345 
 346     /**
 347      * Gets the range of valid values for the specified field.
 348      * <p>
 349      * The range object expresses the minimum and maximum valid values for a field.
 350      * This month-day is used to enhance the accuracy of the returned range.
 351      * If it is not possible to return the range, because the field is not supported
 352      * or for some other reason, an exception is thrown.
 353      * <p>
 354      * If the field is a {@link ChronoField} then the query is implemented here.
 355      * The {@link #isSupported(TemporalField) supported fields} will return
 356      * appropriate range instances.
 357      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 358      * <p>
 359      * If the field is not a {@code ChronoField}, then the result of this method
 360      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
 361      * passing {@code this} as the argument.
 362      * Whether the range can be obtained is determined by the field.
 363      *
 364      * @param field  the field to query the range for, not null
 365      * @return the range of valid values for the field, not null
 366      * @throws DateTimeException if the range for the field cannot be obtained
 367      */
 368     @Override
 369     public ValueRange range(TemporalField field) {
 370         if (field == MONTH_OF_YEAR) {
 371             return field.range();
 372         } else if (field == DAY_OF_MONTH) {
 373             return ValueRange.of(1, getMonth().minLength(), getMonth().maxLength());
 374         }
 375         return TemporalAccessor.super.range(field);
 376     }
 377 
 378     /**
 379      * Gets the value of the specified field from this month-day as an {@code int}.
 380      * <p>
 381      * This queries this month-day for the value for the specified field.
 382      * The returned value will always be within the valid range of values for the field.
 383      * If it is not possible to return the value, because the field is not supported
 384      * or for some other reason, an exception is thrown.
 385      * <p>
 386      * If the field is a {@link ChronoField} then the query is implemented here.
 387      * The {@link #isSupported(TemporalField) supported fields} will return valid
 388      * values based on this month-day.
 389      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 390      * <p>
 391      * If the field is not a {@code ChronoField}, then the result of this method
 392      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 393      * passing {@code this} as the argument. Whether the value can be obtained,
 394      * and what the value represents, is determined by the field.
 395      *
 396      * @param field  the field to get, not null
 397      * @return the value for the field
 398      * @throws DateTimeException if a value for the field cannot be obtained
 399      * @throws ArithmeticException if numeric overflow occurs
 400      */
 401     @Override  // override for Javadoc
 402     public int get(TemporalField field) {
 403         return range(field).checkValidIntValue(getLong(field), field);
 404     }
 405 
 406     /**
 407      * Gets the value of the specified field from this month-day as a {@code long}.
 408      * <p>
 409      * This queries this month-day for the value for the specified field.
 410      * If it is not possible to return the value, because the field is not supported
 411      * or for some other reason, an exception is thrown.
 412      * <p>
 413      * If the field is a {@link ChronoField} then the query is implemented here.
 414      * The {@link #isSupported(TemporalField) supported fields} will return valid
 415      * values based on this month-day.
 416      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 417      * <p>
 418      * If the field is not a {@code ChronoField}, then the result of this method
 419      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 420      * passing {@code this} as the argument. Whether the value can be obtained,
 421      * and what the value represents, is determined by the field.
 422      *
 423      * @param field  the field to get, not null
 424      * @return the value for the field
 425      * @throws DateTimeException if a value for the field cannot be obtained
 426      * @throws ArithmeticException if numeric overflow occurs
 427      */
 428     @Override
 429     public long getLong(TemporalField field) {
 430         if (field instanceof ChronoField) {
 431             switch ((ChronoField) field) {
 432                 // alignedDOW and alignedWOM not supported because they cannot be set in with()
 433                 case DAY_OF_MONTH: return day;
 434                 case MONTH_OF_YEAR: return month;
 435             }
 436             throw new DateTimeException("Unsupported field: " + field.getName());
 437         }
 438         return field.getFrom(this);
 439     }
 440 
 441     //-----------------------------------------------------------------------
 442     /**
 443      * Gets the month-of-year field from 1 to 12.
 444      * <p>
 445      * This method returns the month as an {@code int} from 1 to 12.
 446      * Application code is frequently clearer if the enum {@link Month}
 447      * is used by calling {@link #getMonth()}.
 448      *
 449      * @return the month-of-year, from 1 to 12
 450      * @see #getMonth()
 451      */
 452     public int getMonthValue() {
 453         return month;
 454     }
 455 
 456     /**
 457      * Gets the month-of-year field using the {@code Month} enum.
 458      * <p>
 459      * This method returns the enum {@link Month} for the month.
 460      * This avoids confusion as to what {@code int} values mean.
 461      * If you need access to the primitive {@code int} value then the enum
 462      * provides the {@link Month#getValue() int value}.
 463      *
 464      * @return the month-of-year, not null
 465      * @see #getMonthValue()
 466      */
 467     public Month getMonth() {
 468         return Month.of(month);
 469     }
 470 
 471     /**
 472      * Gets the day-of-month field.
 473      * <p>
 474      * This method returns the primitive {@code int} value for the day-of-month.
 475      *
 476      * @return the day-of-month, from 1 to 31
 477      */
 478     public int getDayOfMonth() {
 479         return day;
 480     }
 481 
 482     //-----------------------------------------------------------------------
 483     /**
 484      * Checks if the year is valid for this month-day.
 485      * <p>


 526      */
 527     public MonthDay with(Month month) {
 528         Objects.requireNonNull(month, "month");
 529         if (month.getValue() == this.month) {
 530             return this;
 531         }
 532         int day = Math.min(this.day, month.maxLength());
 533         return new MonthDay(month.getValue(), day);
 534     }
 535 
 536     /**
 537      * Returns a copy of this {@code MonthDay} with the day-of-month altered.
 538      * <p>
 539      * This returns a month-day with the specified day-of-month.
 540      * If the day-of-month is invalid for the month, an exception is thrown.
 541      * <p>
 542      * This instance is immutable and unaffected by this method call.
 543      *
 544      * @param dayOfMonth  the day-of-month to set in the return month-day, from 1 to 31
 545      * @return a {@code MonthDay} based on this month-day with the requested day, not null
 546      * @throws DateTimeException if the day-of-month value is invalid,
 547      *  or if the day-of-month is invalid for the month
 548      */
 549     public MonthDay withDayOfMonth(int dayOfMonth) {
 550         if (dayOfMonth == this.day) {
 551             return this;
 552         }
 553         return of(month, dayOfMonth);
 554     }
 555 
 556     //-----------------------------------------------------------------------
 557     /**
 558      * Queries this month-day using the specified query.
 559      * <p>
 560      * This queries this month-day using the specified query strategy object.
 561      * The {@code TemporalQuery} object defines the logic to be used to
 562      * obtain the result. Read the documentation of the query to understand
 563      * what the result of this method will be.
 564      * <p>
 565      * The result of this method is obtained by invoking the
 566      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
 567      * specified query passing {@code this} as the argument.
 568      *
 569      * @param <R> the type of the result
 570      * @param query  the query to invoke, not null
 571      * @return the query result, null may be returned (defined by the query)
 572      * @throws DateTimeException if unable to query (defined by the query)
 573      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
 574      */
 575     @SuppressWarnings("unchecked")
 576     @Override
 577     public <R> R query(TemporalQuery<R> query) {
 578         if (query == Queries.chronology()) {
 579             return (R) IsoChronology.INSTANCE;
 580         }
 581         return TemporalAccessor.super.query(query);
 582     }
 583 
 584     /**
 585      * Adjusts the specified temporal object to have this month-day.
 586      * <p>
 587      * This returns a temporal object of the same observable type as the input
 588      * with the month and day-of-month changed to be the same as this.
 589      * <p>
 590      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
 591      * twice, passing {@link ChronoField#MONTH_OF_YEAR} and
 592      * {@link ChronoField#DAY_OF_MONTH} as the fields.
 593      * If the specified temporal object does not use the ISO calendar system then
 594      * a {@code DateTimeException} is thrown.
 595      * <p>
 596      * In most cases, it is clearer to reverse the calling pattern by using
 597      * {@link Temporal#with(TemporalAdjuster)}:
 598      * <pre>
 599      *   // these two lines are equivalent, but the second approach is recommended
 600      *   temporal = thisMonthDay.adjustInto(temporal);
 601      *   temporal = temporal.with(thisMonthDay);
 602      * </pre>
 603      * <p>
 604      * This instance is immutable and unaffected by this method call.
 605      *
 606      * @param temporal  the target object to be adjusted, not null
 607      * @return the adjusted object, not null
 608      * @throws DateTimeException if unable to make the adjustment
 609      * @throws ArithmeticException if numeric overflow occurs
 610      */
 611     @Override
 612     public Temporal adjustInto(Temporal temporal) {
 613         if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
 614             throw new DateTimeException("Adjustment only supported on ISO date-time");
 615         }
 616         temporal = temporal.with(MONTH_OF_YEAR, month);
 617         return temporal.with(DAY_OF_MONTH, Math.min(temporal.range(DAY_OF_MONTH).getMaximum(), day));
 618     }
 619 
 620     //-----------------------------------------------------------------------
 621     /**
 622      * Combines this month-day with a year to create a {@code LocalDate}.
 623      * <p>
 624      * This returns a {@code LocalDate} formed from this month-day and the specified year.
 625      * <p>

 626      * A month-day of February 29th will be adjusted to February 28th in the resulting
 627      * date if the year is not a leap year.
 628      * <p>
 629      * This instance is immutable and unaffected by this method call.
 630      *
 631      * @param year  the year to use, from MIN_YEAR to MAX_YEAR
 632      * @return the local date formed from this month-day and the specified year, not null
 633      * @throws DateTimeException if the year is outside the valid range of years
 634      */
 635     public LocalDate atYear(int year) {
 636         return LocalDate.of(year, month, isValidYear(year) ? day : 28);
 637     }
 638 
 639     //-----------------------------------------------------------------------
 640     /**
 641      * Compares this month-day to another month-day.
 642      * <p>
 643      * The comparison is based first on value of the month, then on the value of the day.
 644      * It is "consistent with equals", as defined by {@link Comparable}.
 645      *
 646      * @param other  the other month-day to compare to, not null
 647      * @return the comparator value, negative if less, positive if greater
 648      */
 649     @Override
 650     public int compareTo(MonthDay other) {
 651         int cmp = (month - other.month);
 652         if (cmp == 0) {
 653             cmp = (day - other.day);
 654         }
 655         return cmp;
 656     }
 657 
 658     /**
 659      * Is this month-day after the specified month-day.
 660      *
 661      * @param other  the other month-day to compare to, not null
 662      * @return true if this is after the specified month-day
 663      */
 664     public boolean isAfter(MonthDay other) {
 665         return compareTo(other) > 0;
 666     }
 667 
 668     /**
 669      * Is this month-day before the specified month-day.


 709     //-----------------------------------------------------------------------
 710     /**
 711      * Outputs this month-day as a {@code String}, such as {@code --12-03}.
 712      * <p>
 713      * The output will be in the format {@code --MM-dd}:
 714      *
 715      * @return a string representation of this month-day, not null
 716      */
 717     @Override
 718     public String toString() {
 719         return new StringBuilder(10).append("--")
 720             .append(month < 10 ? "0" : "").append(month)
 721             .append(day < 10 ? "-0" : "-").append(day)
 722             .toString();
 723     }
 724 
 725     /**
 726      * Outputs this month-day as a {@code String} using the formatter.
 727      * <p>
 728      * This month-day will be passed to the formatter
 729      * {@link DateTimeFormatter#format(TemporalAccessor) format method}.
 730      *
 731      * @param formatter  the formatter to use, not null
 732      * @return the formatted month-day string, not null
 733      * @throws DateTimeException if an error occurs during printing
 734      */
 735     public String toString(DateTimeFormatter formatter) {
 736         Objects.requireNonNull(formatter, "formatter");
 737         return formatter.format(this);
 738     }
 739 
 740     //-----------------------------------------------------------------------
 741     /**
 742      * Writes the object using a
 743      * <a href="../../../serialized-form.html#java.time.temporal.Ser">dedicated serialized form</a>.
 744      * <pre>
 745      *  out.writeByte(13);  // identifies this as a MonthDay
 746      *  out.writeByte(month);
 747      *  out.writeByte(day);
 748      * </pre>
 749      *
 750      * @return the instance of {@code Ser}, not null
 751      */
 752     private Object writeReplace() {
 753         return new Ser(Ser.MONTH_DAY_TYPE, this);
 754     }
 755 
 756     /**
 757      * Defend against malicious streams.
 758      * @return never
 759      * @throws InvalidObjectException always
 760      */
 761     private Object readResolve() throws ObjectStreamException {
 762         throw new InvalidObjectException("Deserialization via serialization delegate");
 763     }
 764 
 765     void writeExternal(DataOutput out) throws IOException {