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