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