1 /* 2 * Copyright (c) 2012, 2018, 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 * This file is available under and governed by the GNU General Public 28 * License version 2 only, as published by the Free Software Foundation. 29 * However, the following notice accompanied the original version of this 30 * file: 31 * 32 * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos 33 * 34 * All rights reserved. 35 * 36 * Redistribution and use in source and binary forms, with or without 37 * modification, are permitted provided that the following conditions are met: 38 * 39 * * Redistributions of source code must retain the above copyright notice, 40 * this list of conditions and the following disclaimer. 41 * 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.ObjectInputStream; 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.Temporal; 80 import java.time.temporal.TemporalAccessor; 81 import java.time.temporal.TemporalAdjuster; 82 import java.time.temporal.TemporalField; 83 import java.time.temporal.TemporalQueries; 84 import java.time.temporal.TemporalQuery; 85 import java.time.temporal.UnsupportedTemporalTypeException; 86 import java.time.temporal.ValueRange; 87 import java.util.Objects; 88 89 /** 90 * A month-day in the ISO-8601 calendar system, such as {@code --12-03}. 91 * <p> 92 * {@code MonthDay} is an immutable date-time object that represents the combination 93 * of a month and day-of-month. Any field that can be derived from a month and day, 94 * such as quarter-of-year, can be obtained. 95 * <p> 96 * This class does not store or represent a year, time or time-zone. 97 * For example, the value "December 3rd" can be stored in a {@code MonthDay}. 98 * <p> 99 * Since a {@code MonthDay} does not possess a year, the leap day of 100 * February 29th is considered valid. 101 * <p> 102 * This class implements {@link TemporalAccessor} rather than {@link Temporal}. 103 * This is because it is not possible to define whether February 29th is valid or not 104 * without external information, preventing the implementation of plus/minus. 105 * Related to this, {@code MonthDay} only provides access to query and set the fields 106 * {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH}. 107 * <p> 108 * The ISO-8601 calendar system is the modern civil calendar system used today 109 * in most of the world. It is equivalent to the proleptic Gregorian calendar 110 * system, in which today's rules for leap years are applied for all time. 111 * For most applications written today, the ISO-8601 rules are entirely suitable. 112 * However, any application that makes use of historical dates, and requires them 113 * to be accurate will find the ISO-8601 approach unsuitable. 114 * 115 * <p> 116 * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a> 117 * class; use of identity-sensitive operations (including reference equality 118 * ({@code ==}), identity hash code, or synchronization) on instances of 119 * {@code MonthDay} may have unpredictable results and should be avoided. 120 * The {@code equals} method should be used for comparisons. 121 * 122 * @implSpec 123 * This class is immutable and thread-safe. 124 * 125 * @since 1.8 126 */ 127 public final class MonthDay 128 implements TemporalAccessor, TemporalAdjuster, Comparable<MonthDay>, Serializable { 129 130 /** 131 * Serialization version. 132 */ 133 @java.io.Serial 134 private static final long serialVersionUID = -939150713474957432L; 135 /** 136 * Parser. 137 */ 138 private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder() 139 .appendLiteral("--") 140 .appendValue(MONTH_OF_YEAR, 2) 141 .appendLiteral('-') 142 .appendValue(DAY_OF_MONTH, 2) 143 .toFormatter(); 144 145 /** 146 * The month-of-year, not null. 147 */ 148 private final int month; 149 /** 150 * The day-of-month. 151 */ 152 private final int day; 153 154 //----------------------------------------------------------------------- 155 /** 156 * Obtains the current month-day from the system clock in the default time-zone. 157 * <p> 158 * This will query the {@link Clock#systemDefaultZone() system clock} in the default 159 * time-zone to obtain the current month-day. 160 * <p> 161 * Using this method will prevent the ability to use an alternate clock for testing 162 * because the clock is hard-coded. 163 * 164 * @return the current month-day using the system clock and default time-zone, not null 165 */ 166 public static MonthDay now() { 167 return now(Clock.systemDefaultZone()); 168 } 169 170 /** 171 * Obtains the current month-day from the system clock in the specified time-zone. 172 * <p> 173 * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current month-day. 174 * Specifying the time-zone avoids dependence on the default time-zone. 175 * <p> 176 * Using this method will prevent the ability to use an alternate clock for testing 177 * because the clock is hard-coded. 178 * 179 * @param zone the zone ID to use, not null 180 * @return the current month-day using the system clock, not null 181 */ 182 public static MonthDay now(ZoneId zone) { 183 return now(Clock.system(zone)); 184 } 185 186 /** 187 * Obtains the current month-day from the specified clock. 188 * <p> 189 * This will query the specified clock to obtain the current month-day. 190 * Using this method allows the use of an alternate clock for testing. 191 * The alternate clock may be introduced using {@link Clock dependency injection}. 192 * 193 * @param clock the clock to use, not null 194 * @return the current month-day, not null 195 */ 196 public static MonthDay now(Clock clock) { 197 final LocalDate now = LocalDate.now(clock); // called once 198 return MonthDay.of(now.getMonth(), now.getDayOfMonth()); 199 } 200 201 //----------------------------------------------------------------------- 202 /** 203 * Obtains an instance of {@code MonthDay}. 204 * <p> 205 * The day-of-month must be valid for the month within a leap year. 206 * Hence, for February, day 29 is valid. 207 * <p> 208 * For example, passing in April and day 31 will throw an exception, as 209 * there can never be April 31st in any year. By contrast, passing in 210 * February 29th is permitted, as that month-day can sometimes be valid. 211 * 212 * @param month the month-of-year to represent, not null 213 * @param dayOfMonth the day-of-month to represent, from 1 to 31 214 * @return the month-day, not null 215 * @throws DateTimeException if the value of any field is out of range, 216 * or if the day-of-month is invalid for the month 217 */ 218 public static MonthDay of(Month month, int dayOfMonth) { 219 Objects.requireNonNull(month, "month"); 220 DAY_OF_MONTH.checkValidValue(dayOfMonth); 221 if (dayOfMonth > month.maxLength()) { 222 throw new DateTimeException("Illegal value for DayOfMonth field, value " + dayOfMonth + 223 " is not valid for month " + month.name()); 224 } 225 return new MonthDay(month.getValue(), dayOfMonth); 226 } 227 228 /** 229 * Obtains an instance of {@code MonthDay}. 230 * <p> 231 * The day-of-month must be valid for the month within a leap year. 232 * Hence, for month 2 (February), day 29 is valid. 233 * <p> 234 * For example, passing in month 4 (April) and day 31 will throw an exception, as 235 * there can never be April 31st in any year. By contrast, passing in 236 * February 29th is permitted, as that month-day can sometimes be valid. 237 * 238 * @param month the month-of-year to represent, from 1 (January) to 12 (December) 239 * @param dayOfMonth the day-of-month to represent, from 1 to 31 240 * @return the month-day, not null 241 * @throws DateTimeException if the value of any field is out of range, 242 * or if the day-of-month is invalid for the month 243 */ 244 public static MonthDay of(int month, int dayOfMonth) { 245 return of(Month.of(month), dayOfMonth); 246 } 247 248 //----------------------------------------------------------------------- 249 /** 250 * Obtains an instance of {@code MonthDay} from a temporal object. 251 * <p> 252 * This obtains a month-day based on the specified temporal. 253 * A {@code TemporalAccessor} represents an arbitrary set of date and time information, 254 * which this factory converts to an instance of {@code MonthDay}. 255 * <p> 256 * The conversion extracts the {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and 257 * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} fields. 258 * The extraction is only permitted if the temporal object has an ISO 259 * chronology, or can be converted to a {@code LocalDate}. 260 * <p> 261 * This method matches the signature of the functional interface {@link TemporalQuery} 262 * allowing it to be used as a query via method reference, {@code MonthDay::from}. 263 * 264 * @param temporal the temporal object to convert, not null 265 * @return the month-day, not null 266 * @throws DateTimeException if unable to convert to a {@code MonthDay} 267 */ 268 public static MonthDay from(TemporalAccessor temporal) { 269 if (temporal instanceof MonthDay) { 270 return (MonthDay) temporal; 271 } 272 try { 273 if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) { 274 temporal = LocalDate.from(temporal); 275 } 276 return of(temporal.get(MONTH_OF_YEAR), temporal.get(DAY_OF_MONTH)); 277 } catch (DateTimeException ex) { 278 throw new DateTimeException("Unable to obtain MonthDay from TemporalAccessor: " + 279 temporal + " of type " + temporal.getClass().getName(), ex); 280 } 281 } 282 283 //----------------------------------------------------------------------- 284 /** 285 * Obtains an instance of {@code MonthDay} from a text string such as {@code --12-03}. 286 * <p> 287 * The string must represent a valid month-day. 288 * The format is {@code --MM-dd}. 289 * 290 * @param text the text to parse such as "--12-03", not null 291 * @return the parsed month-day, not null 292 * @throws DateTimeParseException if the text cannot be parsed 293 */ 294 public static MonthDay parse(CharSequence text) { 295 return parse(text, PARSER); 296 } 297 298 /** 299 * Obtains an instance of {@code MonthDay} from a text string using a specific formatter. 300 * <p> 301 * The text is parsed using the formatter, returning a month-day. 302 * 303 * @param text the text to parse, not null 304 * @param formatter the formatter to use, not null 305 * @return the parsed month-day, not null 306 * @throws DateTimeParseException if the text cannot be parsed 307 */ 308 public static MonthDay parse(CharSequence text, DateTimeFormatter formatter) { 309 Objects.requireNonNull(formatter, "formatter"); 310 return formatter.parse(text, MonthDay::from); 311 } 312 313 //----------------------------------------------------------------------- 314 /** 315 * Constructor, previously validated. 316 * 317 * @param month the month-of-year to represent, validated from 1 to 12 318 * @param dayOfMonth the day-of-month to represent, validated from 1 to 29-31 319 */ 320 private MonthDay(int month, int dayOfMonth) { 321 this.month = month; 322 this.day = dayOfMonth; 323 } 324 325 //----------------------------------------------------------------------- 326 /** 327 * Checks if the specified field is supported. 328 * <p> 329 * This checks if this month-day can be queried for the specified field. 330 * If false, then calling the {@link #range(TemporalField) range} and 331 * {@link #get(TemporalField) get} methods will throw an exception. 332 * <p> 333 * If the field is a {@link ChronoField} then the query is implemented here. 334 * The supported fields are: 335 * <ul> 336 * <li>{@code MONTH_OF_YEAR} 337 * <li>{@code YEAR} 338 * </ul> 339 * All other {@code ChronoField} instances will return false. 340 * <p> 341 * If the field is not a {@code ChronoField}, then the result of this method 342 * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)} 343 * passing {@code this} as the argument. 344 * Whether the field is supported is determined by the field. 345 * 346 * @param field the field to check, null returns false 347 * @return true if the field is supported on this month-day, false if not 348 */ 349 @Override 350 public boolean isSupported(TemporalField field) { 351 if (field instanceof ChronoField) { 352 return field == MONTH_OF_YEAR || field == DAY_OF_MONTH; 353 } 354 return field != null && field.isSupportedBy(this); 355 } 356 357 /** 358 * Gets the range of valid values for the specified field. 359 * <p> 360 * The range object expresses the minimum and maximum valid values for a field. 361 * This month-day is used to enhance the accuracy of the returned range. 362 * If it is not possible to return the range, because the field is not supported 363 * or for some other reason, an exception is thrown. 364 * <p> 365 * If the field is a {@link ChronoField} then the query is implemented here. 366 * The {@link #isSupported(TemporalField) supported fields} will return 367 * appropriate range instances. 368 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 369 * <p> 370 * If the field is not a {@code ChronoField}, then the result of this method 371 * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)} 372 * passing {@code this} as the argument. 373 * Whether the range can be obtained is determined by the field. 374 * 375 * @param field the field to query the range for, not null 376 * @return the range of valid values for the field, not null 377 * @throws DateTimeException if the range for the field cannot be obtained 378 * @throws UnsupportedTemporalTypeException if the field is not supported 379 */ 380 @Override 381 public ValueRange range(TemporalField field) { 382 if (field == MONTH_OF_YEAR) { 383 return field.range(); 384 } else if (field == DAY_OF_MONTH) { 385 return ValueRange.of(1, getMonth().minLength(), getMonth().maxLength()); 386 } 387 return TemporalAccessor.super.range(field); 388 } 389 390 /** 391 * Gets the value of the specified field from this month-day as an {@code int}. 392 * <p> 393 * This queries this month-day for the value of the specified field. 394 * The returned value will always be within the valid range of values for the field. 395 * If it is not possible to return the value, because the field is not supported 396 * or for some other reason, an exception is thrown. 397 * <p> 398 * If the field is a {@link ChronoField} then the query is implemented here. 399 * The {@link #isSupported(TemporalField) supported fields} will return valid 400 * values based on this month-day. 401 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 402 * <p> 403 * If the field is not a {@code ChronoField}, then the result of this method 404 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 405 * passing {@code this} as the argument. Whether the value can be obtained, 406 * and what the value represents, is determined by the field. 407 * 408 * @param field the field to get, not null 409 * @return the value for the field 410 * @throws DateTimeException if a value for the field cannot be obtained or 411 * the value is outside the range of valid values for the field 412 * @throws UnsupportedTemporalTypeException if the field is not supported or 413 * the range of values exceeds an {@code int} 414 * @throws ArithmeticException if numeric overflow occurs 415 */ 416 @Override // override for Javadoc 417 public int get(TemporalField field) { 418 return range(field).checkValidIntValue(getLong(field), field); 419 } 420 421 /** 422 * Gets the value of the specified field from this month-day as a {@code long}. 423 * <p> 424 * This queries this month-day for the value of the specified field. 425 * If it is not possible to return the value, because the field is not supported 426 * or for some other reason, an exception is thrown. 427 * <p> 428 * If the field is a {@link ChronoField} then the query is implemented here. 429 * The {@link #isSupported(TemporalField) supported fields} will return valid 430 * values based on this month-day. 431 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 432 * <p> 433 * If the field is not a {@code ChronoField}, then the result of this method 434 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 435 * passing {@code this} as the argument. Whether the value can be obtained, 436 * and what the value represents, is determined by the field. 437 * 438 * @param field the field to get, not null 439 * @return the value for the field 440 * @throws DateTimeException if a value for the field cannot be obtained 441 * @throws UnsupportedTemporalTypeException if the field is not supported 442 * @throws ArithmeticException if numeric overflow occurs 443 */ 444 @Override 445 public long getLong(TemporalField field) { 446 if (field instanceof ChronoField) { 447 switch ((ChronoField) field) { 448 // alignedDOW and alignedWOM not supported because they cannot be set in with() 449 case DAY_OF_MONTH: return day; 450 case MONTH_OF_YEAR: return month; 451 } 452 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 453 } 454 return field.getFrom(this); 455 } 456 457 //----------------------------------------------------------------------- 458 /** 459 * Gets the month-of-year field from 1 to 12. 460 * <p> 461 * This method returns the month as an {@code int} from 1 to 12. 462 * Application code is frequently clearer if the enum {@link Month} 463 * is used by calling {@link #getMonth()}. 464 * 465 * @return the month-of-year, from 1 to 12 466 * @see #getMonth() 467 */ 468 public int getMonthValue() { 469 return month; 470 } 471 472 /** 473 * Gets the month-of-year field using the {@code Month} enum. 474 * <p> 475 * This method returns the enum {@link Month} for the month. 476 * This avoids confusion as to what {@code int} values mean. 477 * If you need access to the primitive {@code int} value then the enum 478 * provides the {@link Month#getValue() int value}. 479 * 480 * @return the month-of-year, not null 481 * @see #getMonthValue() 482 */ 483 public Month getMonth() { 484 return Month.of(month); 485 } 486 487 /** 488 * Gets the day-of-month field. 489 * <p> 490 * This method returns the primitive {@code int} value for the day-of-month. 491 * 492 * @return the day-of-month, from 1 to 31 493 */ 494 public int getDayOfMonth() { 495 return day; 496 } 497 498 //----------------------------------------------------------------------- 499 /** 500 * Checks if the year is valid for this month-day. 501 * <p> 502 * This method checks whether this month and day and the input year form 503 * a valid date. This can only return false for February 29th. 504 * 505 * @param year the year to validate 506 * @return true if the year is valid for this month-day 507 * @see Year#isValidMonthDay(MonthDay) 508 */ 509 public boolean isValidYear(int year) { 510 return (day == 29 && month == 2 && Year.isLeap(year) == false) == false; 511 } 512 513 //----------------------------------------------------------------------- 514 /** 515 * Returns a copy of this {@code MonthDay} with the month-of-year altered. 516 * <p> 517 * This returns a month-day with the specified month. 518 * If the day-of-month is invalid for the specified month, the day will 519 * be adjusted to the last valid day-of-month. 520 * <p> 521 * This instance is immutable and unaffected by this method call. 522 * 523 * @param month the month-of-year to set in the returned month-day, from 1 (January) to 12 (December) 524 * @return a {@code MonthDay} based on this month-day with the requested month, not null 525 * @throws DateTimeException if the month-of-year value is invalid 526 */ 527 public MonthDay withMonth(int month) { 528 return with(Month.of(month)); 529 } 530 531 /** 532 * Returns a copy of this {@code MonthDay} with the month-of-year altered. 533 * <p> 534 * This returns a month-day with the specified month. 535 * If the day-of-month is invalid for the specified month, the day will 536 * be adjusted to the last valid day-of-month. 537 * <p> 538 * This instance is immutable and unaffected by this method call. 539 * 540 * @param month the month-of-year to set in the returned month-day, not null 541 * @return a {@code MonthDay} based on this month-day with the requested month, not null 542 */ 543 public MonthDay with(Month month) { 544 Objects.requireNonNull(month, "month"); 545 if (month.getValue() == this.month) { 546 return this; 547 } 548 int day = Math.min(this.day, month.maxLength()); 549 return new MonthDay(month.getValue(), day); 550 } 551 552 /** 553 * Returns a copy of this {@code MonthDay} with the day-of-month altered. 554 * <p> 555 * This returns a month-day with the specified day-of-month. 556 * If the day-of-month is invalid for the month, an exception is thrown. 557 * <p> 558 * This instance is immutable and unaffected by this method call. 559 * 560 * @param dayOfMonth the day-of-month to set in the return month-day, from 1 to 31 561 * @return a {@code MonthDay} based on this month-day with the requested day, not null 562 * @throws DateTimeException if the day-of-month value is invalid, 563 * or if the day-of-month is invalid for the month 564 */ 565 public MonthDay withDayOfMonth(int dayOfMonth) { 566 if (dayOfMonth == this.day) { 567 return this; 568 } 569 return of(month, dayOfMonth); 570 } 571 572 //----------------------------------------------------------------------- 573 /** 574 * Queries this month-day using the specified query. 575 * <p> 576 * This queries this month-day using the specified query strategy object. 577 * The {@code TemporalQuery} object defines the logic to be used to 578 * obtain the result. Read the documentation of the query to understand 579 * what the result of this method will be. 580 * <p> 581 * The result of this method is obtained by invoking the 582 * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the 583 * specified query passing {@code this} as the argument. 584 * 585 * @param <R> the type of the result 586 * @param query the query to invoke, not null 587 * @return the query result, null may be returned (defined by the query) 588 * @throws DateTimeException if unable to query (defined by the query) 589 * @throws ArithmeticException if numeric overflow occurs (defined by the query) 590 */ 591 @SuppressWarnings("unchecked") 592 @Override 593 public <R> R query(TemporalQuery<R> query) { 594 if (query == TemporalQueries.chronology()) { 595 return (R) IsoChronology.INSTANCE; 596 } 597 return TemporalAccessor.super.query(query); 598 } 599 600 /** 601 * Adjusts the specified temporal object to have this month-day. 602 * <p> 603 * This returns a temporal object of the same observable type as the input 604 * with the month and day-of-month changed to be the same as this. 605 * <p> 606 * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)} 607 * twice, passing {@link ChronoField#MONTH_OF_YEAR} and 608 * {@link ChronoField#DAY_OF_MONTH} as the fields. 609 * If the specified temporal object does not use the ISO calendar system then 610 * a {@code DateTimeException} is thrown. 611 * <p> 612 * In most cases, it is clearer to reverse the calling pattern by using 613 * {@link Temporal#with(TemporalAdjuster)}: 614 * <pre> 615 * // these two lines are equivalent, but the second approach is recommended 616 * temporal = thisMonthDay.adjustInto(temporal); 617 * temporal = temporal.with(thisMonthDay); 618 * </pre> 619 * <p> 620 * This instance is immutable and unaffected by this method call. 621 * 622 * @param temporal the target object to be adjusted, not null 623 * @return the adjusted object, not null 624 * @throws DateTimeException if unable to make the adjustment 625 * @throws ArithmeticException if numeric overflow occurs 626 */ 627 @Override 628 public Temporal adjustInto(Temporal temporal) { 629 if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) { 630 throw new DateTimeException("Adjustment only supported on ISO date-time"); 631 } 632 temporal = temporal.with(MONTH_OF_YEAR, month); 633 return temporal.with(DAY_OF_MONTH, Math.min(temporal.range(DAY_OF_MONTH).getMaximum(), day)); 634 } 635 636 /** 637 * Formats this month-day using the specified formatter. 638 * <p> 639 * This month-day will be passed to the formatter to produce a string. 640 * 641 * @param formatter the formatter to use, not null 642 * @return the formatted month-day string, not null 643 * @throws DateTimeException if an error occurs during printing 644 */ 645 public String format(DateTimeFormatter formatter) { 646 Objects.requireNonNull(formatter, "formatter"); 647 return formatter.format(this); 648 } 649 650 //----------------------------------------------------------------------- 651 /** 652 * Combines this month-day with a year to create a {@code LocalDate}. 653 * <p> 654 * This returns a {@code LocalDate} formed from this month-day and the specified year. 655 * <p> 656 * A month-day of February 29th will be adjusted to February 28th in the resulting 657 * date if the year is not a leap year. 658 * <p> 659 * This instance is immutable and unaffected by this method call. 660 * 661 * @param year the year to use, from MIN_YEAR to MAX_YEAR 662 * @return the local date formed from this month-day and the specified year, not null 663 * @throws DateTimeException if the year is outside the valid range of years 664 */ 665 public LocalDate atYear(int year) { 666 return LocalDate.of(year, month, isValidYear(year) ? day : 28); 667 } 668 669 //----------------------------------------------------------------------- 670 /** 671 * Compares this month-day to another month-day. 672 * <p> 673 * The comparison is based first on value of the month, then on the value of the day. 674 * It is "consistent with equals", as defined by {@link Comparable}. 675 * 676 * @param other the other month-day to compare to, not null 677 * @return the comparator value, negative if less, positive if greater 678 */ 679 @Override 680 public int compareTo(MonthDay other) { 681 int cmp = (month - other.month); 682 if (cmp == 0) { 683 cmp = (day - other.day); 684 } 685 return cmp; 686 } 687 688 /** 689 * Checks if this month-day is after the specified month-day. 690 * 691 * @param other the other month-day to compare to, not null 692 * @return true if this is after the specified month-day 693 */ 694 public boolean isAfter(MonthDay other) { 695 return compareTo(other) > 0; 696 } 697 698 /** 699 * Checks if this month-day is before the specified month-day. 700 * 701 * @param other the other month-day to compare to, not null 702 * @return true if this point is before the specified month-day 703 */ 704 public boolean isBefore(MonthDay other) { 705 return compareTo(other) < 0; 706 } 707 708 //----------------------------------------------------------------------- 709 /** 710 * Checks if this month-day is equal to another month-day. 711 * <p> 712 * The comparison is based on the time-line position of the month-day within a year. 713 * 714 * @param obj the object to check, null returns false 715 * @return true if this is equal to the other month-day 716 */ 717 @Override 718 public boolean equals(Object obj) { 719 if (this == obj) { 720 return true; 721 } 722 if (obj instanceof MonthDay) { 723 MonthDay other = (MonthDay) obj; 724 return month == other.month && day == other.day; 725 } 726 return false; 727 } 728 729 /** 730 * A hash code for this month-day. 731 * 732 * @return a suitable hash code 733 */ 734 @Override 735 public int hashCode() { 736 return (month << 6) + day; 737 } 738 739 //----------------------------------------------------------------------- 740 /** 741 * Outputs this month-day as a {@code String}, such as {@code --12-03}. 742 * <p> 743 * The output will be in the format {@code --MM-dd}: 744 * 745 * @return a string representation of this month-day, not null 746 */ 747 @Override 748 public String toString() { 749 return new StringBuilder(10).append("--") 750 .append(month < 10 ? "0" : "").append(month) 751 .append(day < 10 ? "-0" : "-").append(day) 752 .toString(); 753 } 754 755 //----------------------------------------------------------------------- 756 /** 757 * Writes the object using a 758 * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>. 759 * @serialData 760 * <pre> 761 * out.writeByte(13); // identifies a MonthDay 762 * out.writeByte(month); 763 * out.writeByte(day); 764 * </pre> 765 * 766 * @return the instance of {@code Ser}, not null 767 */ 768 @java.io.Serial 769 private Object writeReplace() { 770 return new Ser(Ser.MONTH_DAY_TYPE, this); 771 } 772 773 /** 774 * Defend against malicious streams. 775 * 776 * @param s the stream to read 777 * @throws InvalidObjectException always 778 */ 779 @java.io.Serial 780 private void readObject(ObjectInputStream s) throws InvalidObjectException { 781 throw new InvalidObjectException("Deserialization via serialization delegate"); 782 } 783 784 void writeExternal(DataOutput out) throws IOException { 785 out.writeByte(month); 786 out.writeByte(day); 787 } 788 789 static MonthDay readExternal(DataInput in) throws IOException { 790 byte month = in.readByte(); 791 byte day = in.readByte(); 792 return MonthDay.of(month, day); 793 } 794 795 }