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.ERA;
65 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
66 import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;
67 import static java.time.temporal.ChronoField.YEAR;
68 import static java.time.temporal.ChronoField.YEAR_OF_ERA;
69 import static java.time.temporal.ChronoUnit.CENTURIES;
70 import static java.time.temporal.ChronoUnit.DECADES;
71 import static java.time.temporal.ChronoUnit.ERAS;
72 import static java.time.temporal.ChronoUnit.MILLENNIA;
73 import static java.time.temporal.ChronoUnit.MONTHS;
74 import static java.time.temporal.ChronoUnit.YEARS;
75
76 import java.io.DataInput;
77 import java.io.DataOutput;
78 import java.io.IOException;
79 import java.io.InvalidObjectException;
80 import java.io.ObjectInputStream;
81 import java.io.ObjectStreamField;
82 import java.io.Serial;
83 import java.io.Serializable;
84 import java.time.chrono.Chronology;
85 import java.time.chrono.IsoChronology;
86 import java.time.format.DateTimeFormatter;
87 import java.time.format.DateTimeFormatterBuilder;
88 import java.time.format.DateTimeParseException;
89 import java.time.format.SignStyle;
90 import java.time.temporal.ChronoField;
91 import java.time.temporal.ChronoUnit;
92 import java.time.temporal.Temporal;
93 import java.time.temporal.TemporalAccessor;
94 import java.time.temporal.TemporalAdjuster;
95 import java.time.temporal.TemporalAmount;
96 import java.time.temporal.TemporalField;
97 import java.time.temporal.TemporalQueries;
98 import java.time.temporal.TemporalQuery;
99 import java.time.temporal.TemporalUnit;
100 import java.time.temporal.UnsupportedTemporalTypeException;
101 import java.time.temporal.ValueRange;
102 import java.util.Objects;
103
104 import jdk.internal.util.DecimalDigits;
105
106 /**
107 * A year-month in the ISO-8601 calendar system, such as {@code 2007-12}.
108 * <p>
109 * {@code YearMonth} is an immutable date-time object that represents the combination
110 * of a year and month. Any field that can be derived from a year and month, such as
111 * quarter-of-year, can be obtained.
112 * <p>
113 * This class does not store or represent a day, time or time-zone.
114 * For example, the value "October 2007" can be stored in a {@code YearMonth}.
115 * <p>
116 * The ISO-8601 calendar system is the modern civil calendar system used today
117 * in most of the world. It is equivalent to the proleptic Gregorian calendar
118 * system, in which today's rules for leap years are applied for all time.
119 * For most applications written today, the ISO-8601 rules are entirely suitable.
120 * However, any application that makes use of historical dates, and requires them
121 * to be accurate will find the ISO-8601 approach unsuitable.
122 * <p>
123 * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
124 * class; programmers should treat instances that are {@linkplain #equals(Object) equal}
125 * as interchangeable and should not use instances for synchronization, mutexes, or
126 * with {@linkplain java.lang.ref.Reference object references}.
127 *
128 * <div class="preview-block">
129 * <div class="preview-comment">
130 * When preview features are enabled, {@code YearMonth} is a {@linkplain Class#isValue value class}.
131 * Use of value class instances for synchronization, mutexes, or with
132 * {@linkplain java.lang.ref.Reference object references} result in
133 * {@link IdentityException}.
134 * </div>
135 * </div>
136 *
137 * @implSpec
138 * This class is immutable and thread-safe.
139 *
140 * @since 1.8
141 */
142 @jdk.internal.ValueBased
143 @jdk.internal.MigratedValueClass
144 public final class YearMonth
145 implements Temporal, TemporalAdjuster, Comparable<YearMonth>, Serializable {
146
147 /**
148 * Serialization version.
149 */
150 @java.io.Serial
151 private static final long serialVersionUID = 4183400860270640070L;
152
153 /**
154 * For backward compatibility of the serialized {@code YearMonth.class} object,
155 * explicitly declare the types of the serialized fields as defined in Java SE 8.
156 * Instances of {@code YearMonth} are serialized using the dedicated
157 * serialized form by {@code writeReplace}.
158 * @serialField year int The year.
159 * @serialField month int The month-of-year.
160 */
161 @java.io.Serial
162 private static final ObjectStreamField[] serialPersistentFields = {
163 new ObjectStreamField("year", int.class),
164 new ObjectStreamField("month", int.class),
165 };
166 /**
167 * Parser.
168 */
169 private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
170 .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
171 .appendLiteral('-')
172 .appendValue(MONTH_OF_YEAR, 2)
173 .toFormatter();
174
175 /**
176 * @serial The year.
177 */
178 private final transient int year;
179 /**
180 * @serial The month-of-year..
181 */
182 private final transient byte month;
183
184 //-----------------------------------------------------------------------
185 /**
186 * Obtains the current year-month from the system clock in the default time-zone.
187 * <p>
188 * This will query the {@link Clock#systemDefaultZone() system clock} in the default
189 * time-zone to obtain the current year-month.
190 * <p>
191 * Using this method will prevent the ability to use an alternate clock for testing
192 * because the clock is hard-coded.
193 *
194 * @return the current year-month using the system clock and default time-zone, not null
195 */
196 public static YearMonth now() {
197 return now(Clock.systemDefaultZone());
198 }
199
200 /**
201 * Obtains the current year-month from the system clock in the specified time-zone.
202 * <p>
203 * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current year-month.
204 * Specifying the time-zone avoids dependence on the default time-zone.
205 * <p>
206 * Using this method will prevent the ability to use an alternate clock for testing
207 * because the clock is hard-coded.
208 *
209 * @param zone the zone ID to use, not null
210 * @return the current year-month using the system clock, not null
211 */
212 public static YearMonth now(ZoneId zone) {
213 return now(Clock.system(zone));
214 }
215
216 /**
217 * Obtains the current year-month from the specified clock.
218 * <p>
219 * This will query the specified clock to obtain the current year-month.
220 * Using this method allows the use of an alternate clock for testing.
221 * The alternate clock may be introduced using {@link Clock dependency injection}.
222 *
223 * @param clock the clock to use, not null
224 * @return the current year-month, not null
225 */
226 public static YearMonth now(Clock clock) {
227 final LocalDate now = LocalDate.now(clock); // called once
228 return YearMonth.of(now.getYear(), now.getMonth());
229 }
230
231 //-----------------------------------------------------------------------
232 /**
233 * Obtains an instance of {@code YearMonth} from a year and month.
234 *
235 * @param year the year to represent, from MIN_YEAR to MAX_YEAR
236 * @param month the month-of-year to represent, not null
237 * @return the year-month, not null
238 * @throws DateTimeException if the year value is invalid
239 */
240 public static YearMonth of(int year, Month month) {
241 Objects.requireNonNull(month, "month");
242 return of(year, month.getValue());
243 }
244
245 /**
246 * Obtains an instance of {@code YearMonth} from a year and month.
247 *
248 * @param year the year to represent, from MIN_YEAR to MAX_YEAR
249 * @param month the month-of-year to represent, from 1 (January) to 12 (December)
250 * @return the year-month, not null
251 * @throws DateTimeException if either field value is invalid
252 */
253 public static YearMonth of(int year, int month) {
254 YEAR.checkValidValue(year);
255 MONTH_OF_YEAR.checkValidValue(month);
256 return new YearMonth(year, month);
257 }
258
259 //-----------------------------------------------------------------------
260 /**
261 * Obtains an instance of {@code YearMonth} from a temporal object.
262 * <p>
263 * This obtains a year-month based on the specified temporal.
264 * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
265 * which this factory converts to an instance of {@code YearMonth}.
266 * <p>
267 * The conversion extracts the {@link ChronoField#YEAR YEAR} and
268 * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} fields.
269 * The extraction is only permitted if the temporal object has an ISO
270 * chronology, or can be converted to a {@code LocalDate}.
271 * <p>
272 * This method matches the signature of the functional interface {@link TemporalQuery}
273 * allowing it to be used as a query via method reference, {@code YearMonth::from}.
274 *
275 * @param temporal the temporal object to convert, not null
276 * @return the year-month, not null
277 * @throws DateTimeException if unable to convert to a {@code YearMonth}
278 */
279 public static YearMonth from(TemporalAccessor temporal) {
280 if (temporal instanceof YearMonth) {
281 return (YearMonth) temporal;
282 }
283 Objects.requireNonNull(temporal, "temporal");
284 try {
285 if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
286 temporal = LocalDate.from(temporal);
287 }
288 return of(temporal.get(YEAR), temporal.get(MONTH_OF_YEAR));
289 } catch (DateTimeException ex) {
290 throw new DateTimeException("Unable to obtain YearMonth from TemporalAccessor: " +
291 temporal + " of type " + temporal.getClass().getName(), ex);
292 }
293 }
294
295 //-----------------------------------------------------------------------
296 /**
297 * Obtains an instance of {@code YearMonth} from a text string such as {@code 2007-12}.
298 * <p>
299 * The string must represent a valid year-month.
300 * The format must be {@code uuuu-MM}.
301 * Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.
302 *
303 * @param text the text to parse such as "2007-12", not null
304 * @return the parsed year-month, not null
305 * @throws DateTimeParseException if the text cannot be parsed
306 */
307 public static YearMonth parse(CharSequence text) {
308 return parse(text, PARSER);
309 }
310
311 /**
312 * Obtains an instance of {@code YearMonth} from a text string using a specific formatter.
313 * <p>
314 * The text is parsed using the formatter, returning a year-month.
315 *
316 * @param text the text to parse, not null
317 * @param formatter the formatter to use, not null
318 * @return the parsed year-month, not null
319 * @throws DateTimeParseException if the text cannot be parsed
320 */
321 public static YearMonth parse(CharSequence text, DateTimeFormatter formatter) {
322 Objects.requireNonNull(formatter, "formatter");
323 return formatter.parse(text, YearMonth::from);
324 }
325
326 //-----------------------------------------------------------------------
327 /**
328 * Constructor.
329 *
330 * @param year the year to represent, validated from MIN_YEAR to MAX_YEAR
331 * @param month the month-of-year to represent, validated from 1 (January) to 12 (December)
332 */
333 private YearMonth(int year, int month) {
334 this.year = year;
335 this.month = (byte) month;
336 }
337
338 /**
339 * Returns a copy of this year-month with the new year and month, checking
340 * to see if a new object is in fact required.
341 *
342 * @param newYear the year to represent, validated from MIN_YEAR to MAX_YEAR
343 * @param newMonth the month-of-year to represent, validated not null
344 * @return the year-month, not null
345 */
346 private YearMonth with(int newYear, int newMonth) {
347 if (year == newYear && month == newMonth) {
348 return this;
349 }
350 return new YearMonth(newYear, newMonth);
351 }
352
353 //-----------------------------------------------------------------------
354 /**
355 * Checks if the specified field is supported.
356 * <p>
357 * This checks if this year-month can be queried for the specified field.
358 * If false, then calling the {@link #range(TemporalField) range},
359 * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
360 * methods will throw an exception.
361 * <p>
362 * If the field is a {@link ChronoField} then the query is implemented here.
363 * The supported fields are:
364 * <ul>
365 * <li>{@code MONTH_OF_YEAR}
366 * <li>{@code PROLEPTIC_MONTH}
367 * <li>{@code YEAR_OF_ERA}
368 * <li>{@code YEAR}
369 * <li>{@code ERA}
370 * </ul>
371 * All other {@code ChronoField} instances will return false.
372 * <p>
373 * If the field is not a {@code ChronoField}, then the result of this method
374 * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
375 * passing {@code this} as the argument.
376 * Whether the field is supported is determined by the field.
377 *
378 * @param field the field to check, null returns false
379 * @return true if the field is supported on this year-month, false if not
380 */
381 @Override
382 public boolean isSupported(TemporalField field) {
383 if (field instanceof ChronoField) {
384 return field == YEAR || field == MONTH_OF_YEAR ||
385 field == PROLEPTIC_MONTH || field == YEAR_OF_ERA || field == ERA;
386 }
387 return field != null && field.isSupportedBy(this);
388 }
389
390 /**
391 * Checks if the specified unit is supported.
392 * <p>
393 * This checks if the specified unit can be added to, or subtracted from, this year-month.
394 * If false, then calling the {@link #plus(long, TemporalUnit)} and
395 * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
396 * <p>
397 * If the unit is a {@link ChronoUnit} then the query is implemented here.
398 * The supported units are:
399 * <ul>
400 * <li>{@code MONTHS}
401 * <li>{@code YEARS}
402 * <li>{@code DECADES}
403 * <li>{@code CENTURIES}
404 * <li>{@code MILLENNIA}
405 * <li>{@code ERAS}
406 * </ul>
407 * All other {@code ChronoUnit} instances will return false.
408 * <p>
409 * If the unit is not a {@code ChronoUnit}, then the result of this method
410 * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
411 * passing {@code this} as the argument.
412 * Whether the unit is supported is determined by the unit.
413 *
414 * @param unit the unit to check, null returns false
415 * @return true if the unit can be added/subtracted, false if not
416 */
417 @Override
418 public boolean isSupported(TemporalUnit unit) {
419 if (unit instanceof ChronoUnit) {
420 return unit == MONTHS || unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS;
421 }
422 return unit != null && unit.isSupportedBy(this);
423 }
424
425 //-----------------------------------------------------------------------
426 /**
427 * Gets the range of valid values for the specified field.
428 * <p>
429 * The range object expresses the minimum and maximum valid values for a field.
430 * This year-month is used to enhance the accuracy of the returned range.
431 * If it is not possible to return the range, because the field is not supported
432 * or for some other reason, an exception is thrown.
433 * <p>
434 * If the field is a {@link ChronoField} then the query is implemented here.
435 * The {@link #isSupported(TemporalField) supported fields} will return
436 * appropriate range instances.
437 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
438 * <p>
439 * If the field is not a {@code ChronoField}, then the result of this method
440 * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
441 * passing {@code this} as the argument.
442 * Whether the range can be obtained is determined by the field.
443 *
444 * @param field the field to query the range for, not null
445 * @return the range of valid values for the field, not null
446 * @throws DateTimeException if the range for the field cannot be obtained
447 * @throws UnsupportedTemporalTypeException if the field is not supported
448 */
449 @Override
450 public ValueRange range(TemporalField field) {
451 if (field == YEAR_OF_ERA) {
452 return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));
453 }
454 return Temporal.super.range(field);
455 }
456
457 /**
458 * Gets the value of the specified field from this year-month as an {@code int}.
459 * <p>
460 * This queries this year-month for the value of the specified field.
461 * The returned value will always be within the valid range of values for the field.
462 * If it is not possible to return the value, because the field is not supported
463 * or for some other reason, an exception is thrown.
464 * <p>
465 * If the field is a {@link ChronoField} then the query is implemented here.
466 * The {@link #isSupported(TemporalField) supported fields} will return valid
467 * values based on this year-month, except {@code PROLEPTIC_MONTH} which is too
468 * large to fit in an {@code int} and throw a {@code DateTimeException}.
469 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
470 * <p>
471 * If the field is not a {@code ChronoField}, then the result of this method
472 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
473 * passing {@code this} as the argument. Whether the value can be obtained,
474 * and what the value represents, is determined by the field.
475 *
476 * @param field the field to get, not null
477 * @return the value for the field
478 * @throws DateTimeException if a value for the field cannot be obtained or
479 * the value is outside the range of valid values for the field
480 * @throws UnsupportedTemporalTypeException if the field is not supported or
481 * the range of values exceeds an {@code int}
482 * @throws ArithmeticException if numeric overflow occurs
483 */
484 @Override // override for Javadoc
485 public int get(TemporalField field) {
486 return range(field).checkValidIntValue(getLong(field), field);
487 }
488
489 /**
490 * Gets the value of the specified field from this year-month as a {@code long}.
491 * <p>
492 * This queries this year-month for the value of the specified field.
493 * If it is not possible to return the value, because the field is not supported
494 * or for some other reason, an exception is thrown.
495 * <p>
496 * If the field is a {@link ChronoField} then the query is implemented here.
497 * The {@link #isSupported(TemporalField) supported fields} will return valid
498 * values based on this year-month.
499 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
500 * <p>
501 * If the field is not a {@code ChronoField}, then the result of this method
502 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
503 * passing {@code this} as the argument. Whether the value can be obtained,
504 * and what the value represents, is determined by the field.
505 *
506 * @param field the field to get, not null
507 * @return the value for the field
508 * @throws DateTimeException if a value for the field cannot be obtained
509 * @throws UnsupportedTemporalTypeException if the field is not supported
510 * @throws ArithmeticException if numeric overflow occurs
511 */
512 @Override
513 public long getLong(TemporalField field) {
514 if (field instanceof ChronoField chronoField) {
515 return switch (chronoField) {
516 case MONTH_OF_YEAR -> month;
517 case PROLEPTIC_MONTH -> getProlepticMonth();
518 case YEAR_OF_ERA -> (year < 1 ? 1 - year : year);
519 case YEAR -> year;
520 case ERA -> (year < 1 ? 0 : 1);
521 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
522 };
523 }
524 return field.getFrom(this);
525 }
526
527 private long getProlepticMonth() {
528 return (year * 12L + month - 1);
529 }
530
531 //-----------------------------------------------------------------------
532 /**
533 * Gets the year field.
534 * <p>
535 * This method returns the primitive {@code int} value for the year.
536 * <p>
537 * The year returned by this method is proleptic as per {@code get(YEAR)}.
538 *
539 * @return the year, from MIN_YEAR to MAX_YEAR
540 */
541 public int getYear() {
542 return year;
543 }
544
545 /**
546 * Gets the month-of-year field from 1 to 12.
547 * <p>
548 * This method returns the month as an {@code int} from 1 to 12.
549 * Application code is frequently clearer if the enum {@link Month}
550 * is used by calling {@link #getMonth()}.
551 *
552 * @return the month-of-year, from 1 to 12
553 * @see #getMonth()
554 */
555 public int getMonthValue() {
556 return month;
557 }
558
559 /**
560 * Gets the month-of-year field using the {@code Month} enum.
561 * <p>
562 * This method returns the enum {@link Month} for the month.
563 * This avoids confusion as to what {@code int} values mean.
564 * If you need access to the primitive {@code int} value then the enum
565 * provides the {@link Month#getValue() int value}.
566 *
567 * @return the month-of-year, not null
568 * @see #getMonthValue()
569 */
570 public Month getMonth() {
571 return Month.of(month);
572 }
573
574 //-----------------------------------------------------------------------
575 /**
576 * Checks if the year is a leap year, according to the ISO proleptic
577 * calendar system rules.
578 * <p>
579 * This method applies the current rules for leap years across the whole time-line.
580 * In general, a year is a leap year if it is divisible by four without
581 * remainder. However, years divisible by 100, are not leap years, with
582 * the exception of years divisible by 400 which are.
583 * <p>
584 * For example, 1904 is a leap year it is divisible by 4.
585 * 1900 was not a leap year as it is divisible by 100, however 2000 was a
586 * leap year as it is divisible by 400.
587 * <p>
588 * The calculation is proleptic - applying the same rules into the far future and far past.
589 * This is historically inaccurate, but is correct for the ISO-8601 standard.
590 *
591 * @return true if the year is leap, false otherwise
592 */
593 public boolean isLeapYear() {
594 return IsoChronology.INSTANCE.isLeapYear(year);
595 }
596
597 /**
598 * Checks if the day-of-month is valid for this year-month.
599 * <p>
600 * This method checks whether this year and month and the input day form
601 * a valid date.
602 *
603 * @param dayOfMonth the day-of-month to validate, from 1 to 31, invalid value returns false
604 * @return true if the day is valid for this year-month
605 */
606 public boolean isValidDay(int dayOfMonth) {
607 return dayOfMonth >= 1 && dayOfMonth <= lengthOfMonth();
608 }
609
610 /**
611 * Returns the length of the month, taking account of the year.
612 * <p>
613 * This returns the length of the month in days.
614 * For example, a date in January would return 31.
615 *
616 * @return the length of the month in days, from 28 to 31
617 */
618 public int lengthOfMonth() {
619 return getMonth().length(isLeapYear());
620 }
621
622 /**
623 * Returns the length of the year.
624 * <p>
625 * This returns the length of the year in days, either 365 or 366.
626 *
627 * @return 366 if the year is leap, 365 otherwise
628 */
629 public int lengthOfYear() {
630 return (isLeapYear() ? 366 : 365);
631 }
632
633 //-----------------------------------------------------------------------
634 /**
635 * Returns an adjusted copy of this year-month.
636 * <p>
637 * This returns a {@code YearMonth}, based on this one, with the year-month adjusted.
638 * The adjustment takes place using the specified adjuster strategy object.
639 * Read the documentation of the adjuster to understand what adjustment will be made.
640 * <p>
641 * A simple adjuster might simply set the one of the fields, such as the year field.
642 * A more complex adjuster might set the year-month to the next month that
643 * Halley's comet will pass the Earth.
644 * <p>
645 * The result of this method is obtained by invoking the
646 * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
647 * specified adjuster passing {@code this} as the argument.
648 * <p>
649 * This instance is immutable and unaffected by this method call.
650 *
651 * @param adjuster the adjuster to use, not null
652 * @return a {@code YearMonth} based on {@code this} with the adjustment made, not null
653 * @throws DateTimeException if the adjustment cannot be made
654 * @throws ArithmeticException if numeric overflow occurs
655 */
656 @Override
657 public YearMonth with(TemporalAdjuster adjuster) {
658 return (YearMonth) adjuster.adjustInto(this);
659 }
660
661 /**
662 * Returns a copy of this year-month with the specified field set to a new value.
663 * <p>
664 * This returns a {@code YearMonth}, based on this one, with the value
665 * for the specified field changed.
666 * This can be used to change any supported field, such as the year or month.
667 * If it is not possible to set the value, because the field is not supported or for
668 * some other reason, an exception is thrown.
669 * <p>
670 * If the field is a {@link ChronoField} then the adjustment is implemented here.
671 * The supported fields behave as follows:
672 * <ul>
673 * <li>{@code MONTH_OF_YEAR} -
674 * Returns a {@code YearMonth} with the specified month-of-year.
675 * The year will be unchanged.
676 * <li>{@code PROLEPTIC_MONTH} -
677 * Returns a {@code YearMonth} with the specified proleptic-month.
678 * This completely replaces the year and month of this object.
679 * <li>{@code YEAR_OF_ERA} -
680 * Returns a {@code YearMonth} with the specified year-of-era
681 * The month and era will be unchanged.
682 * <li>{@code YEAR} -
683 * Returns a {@code YearMonth} with the specified year.
684 * The month will be unchanged.
685 * <li>{@code ERA} -
686 * Returns a {@code YearMonth} with the specified era.
687 * The month and year-of-era will be unchanged.
688 * </ul>
689 * <p>
690 * In all cases, if the new value is outside the valid range of values for the field
691 * then a {@code DateTimeException} will be thrown.
692 * <p>
693 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
694 * <p>
695 * If the field is not a {@code ChronoField}, then the result of this method
696 * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
697 * passing {@code this} as the argument. In this case, the field determines
698 * whether and how to adjust the instant.
699 * <p>
700 * This instance is immutable and unaffected by this method call.
701 *
702 * @param field the field to set in the result, not null
703 * @param newValue the new value of the field in the result
704 * @return a {@code YearMonth} based on {@code this} with the specified field set, not null
705 * @throws DateTimeException if the field cannot be set
706 * @throws UnsupportedTemporalTypeException if the field is not supported
707 * @throws ArithmeticException if numeric overflow occurs
708 */
709 @Override
710 public YearMonth with(TemporalField field, long newValue) {
711 if (field instanceof ChronoField chronoField) {
712 chronoField.checkValidValue(newValue);
713 return switch (chronoField) {
714 case MONTH_OF_YEAR -> withMonth((int) newValue);
715 case PROLEPTIC_MONTH -> plusMonths(newValue - getProlepticMonth());
716 case YEAR_OF_ERA -> withYear((int) (year < 1 ? 1 - newValue : newValue));
717 case YEAR -> withYear((int) newValue);
718 case ERA -> (getLong(ERA) == newValue ? this : withYear(1 - year));
719 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
720 };
721 }
722 return field.adjustInto(this, newValue);
723 }
724
725 //-----------------------------------------------------------------------
726 /**
727 * Returns a copy of this {@code YearMonth} with the year altered.
728 * <p>
729 * This instance is immutable and unaffected by this method call.
730 *
731 * @param year the year to set in the returned year-month, from MIN_YEAR to MAX_YEAR
732 * @return a {@code YearMonth} based on this year-month with the requested year, not null
733 * @throws DateTimeException if the year value is invalid
734 */
735 public YearMonth withYear(int year) {
736 YEAR.checkValidValue(year);
737 return with(year, month);
738 }
739
740 /**
741 * Returns a copy of this {@code YearMonth} with the month-of-year altered.
742 * <p>
743 * This instance is immutable and unaffected by this method call.
744 *
745 * @param month the month-of-year to set in the returned year-month, from 1 (January) to 12 (December)
746 * @return a {@code YearMonth} based on this year-month with the requested month, not null
747 * @throws DateTimeException if the month-of-year value is invalid
748 */
749 public YearMonth withMonth(int month) {
750 MONTH_OF_YEAR.checkValidValue(month);
751 return with(year, month);
752 }
753
754 //-----------------------------------------------------------------------
755 /**
756 * Returns a copy of this year-month with the specified amount added.
757 * <p>
758 * This returns a {@code YearMonth}, based on this one, with the specified amount added.
759 * The amount is typically {@link Period} but may be any other type implementing
760 * the {@link TemporalAmount} interface.
761 * <p>
762 * The calculation is delegated to the amount object by calling
763 * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
764 * to implement the addition in any way it wishes, however it typically
765 * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
766 * of the amount implementation to determine if it can be successfully added.
767 * <p>
768 * This instance is immutable and unaffected by this method call.
769 *
770 * @param amountToAdd the amount to add, not null
771 * @return a {@code YearMonth} based on this year-month with the addition made, not null
772 * @throws DateTimeException if the addition cannot be made
773 * @throws ArithmeticException if numeric overflow occurs
774 */
775 @Override
776 public YearMonth plus(TemporalAmount amountToAdd) {
777 return (YearMonth) amountToAdd.addTo(this);
778 }
779
780 /**
781 * Returns a copy of this year-month with the specified amount added.
782 * <p>
783 * This returns a {@code YearMonth}, based on this one, with the amount
784 * in terms of the unit added. If it is not possible to add the amount, because the
785 * unit is not supported or for some other reason, an exception is thrown.
786 * <p>
787 * If the field is a {@link ChronoUnit} then the addition is implemented here.
788 * The supported fields behave as follows:
789 * <ul>
790 * <li>{@code MONTHS} -
791 * Returns a {@code YearMonth} with the specified number of months added.
792 * This is equivalent to {@link #plusMonths(long)}.
793 * <li>{@code YEARS} -
794 * Returns a {@code YearMonth} with the specified number of years added.
795 * This is equivalent to {@link #plusYears(long)}.
796 * <li>{@code DECADES} -
797 * Returns a {@code YearMonth} with the specified number of decades added.
798 * This is equivalent to calling {@link #plusYears(long)} with the amount
799 * multiplied by 10.
800 * <li>{@code CENTURIES} -
801 * Returns a {@code YearMonth} with the specified number of centuries added.
802 * This is equivalent to calling {@link #plusYears(long)} with the amount
803 * multiplied by 100.
804 * <li>{@code MILLENNIA} -
805 * Returns a {@code YearMonth} with the specified number of millennia added.
806 * This is equivalent to calling {@link #plusYears(long)} with the amount
807 * multiplied by 1,000.
808 * <li>{@code ERAS} -
809 * Returns a {@code YearMonth} with the specified number of eras added.
810 * Only two eras are supported so the amount must be one, zero or minus one.
811 * If the amount is non-zero then the year is changed such that the year-of-era
812 * is unchanged.
813 * </ul>
814 * <p>
815 * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.
816 * <p>
817 * If the field is not a {@code ChronoUnit}, then the result of this method
818 * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
819 * passing {@code this} as the argument. In this case, the unit determines
820 * whether and how to perform the addition.
821 * <p>
822 * This instance is immutable and unaffected by this method call.
823 *
824 * @param amountToAdd the amount of the unit to add to the result, may be negative
825 * @param unit the unit of the amount to add, not null
826 * @return a {@code YearMonth} based on this year-month with the specified amount added, not null
827 * @throws DateTimeException if the addition cannot be made
828 * @throws UnsupportedTemporalTypeException if the unit is not supported
829 * @throws ArithmeticException if numeric overflow occurs
830 */
831 @Override
832 public YearMonth plus(long amountToAdd, TemporalUnit unit) {
833 if (unit instanceof ChronoUnit chronoUnit) {
834 return switch (chronoUnit) {
835 case MONTHS -> plusMonths(amountToAdd);
836 case YEARS -> plusYears(amountToAdd);
837 case DECADES -> plusYears(Math.multiplyExact(amountToAdd, 10));
838 case CENTURIES -> plusYears(Math.multiplyExact(amountToAdd, 100));
839 case MILLENNIA -> plusYears(Math.multiplyExact(amountToAdd, 1000));
840 case ERAS -> with(ERA, Math.addExact(getLong(ERA), amountToAdd));
841 default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
842 };
843 }
844 return unit.addTo(this, amountToAdd);
845 }
846
847 /**
848 * Returns a copy of this {@code YearMonth} with the specified number of years added.
849 * <p>
850 * This instance is immutable and unaffected by this method call.
851 *
852 * @param yearsToAdd the years to add, may be negative
853 * @return a {@code YearMonth} based on this year-month with the years added, not null
854 * @throws DateTimeException if the result exceeds the supported range
855 */
856 public YearMonth plusYears(long yearsToAdd) {
857 if (yearsToAdd == 0) {
858 return this;
859 }
860 int newYear = YEAR.checkValidIntValue(year + yearsToAdd); // safe overflow
861 return with(newYear, month);
862 }
863
864 /**
865 * Returns a copy of this {@code YearMonth} with the specified number of months added.
866 * <p>
867 * This instance is immutable and unaffected by this method call.
868 *
869 * @param monthsToAdd the months to add, may be negative
870 * @return a {@code YearMonth} based on this year-month with the months added, not null
871 * @throws DateTimeException if the result exceeds the supported range
872 */
873 public YearMonth plusMonths(long monthsToAdd) {
874 if (monthsToAdd == 0) {
875 return this;
876 }
877 long monthCount = year * 12L + (month - 1);
878 long calcMonths = monthCount + monthsToAdd; // safe overflow
879 int newYear = YEAR.checkValidIntValue(Math.floorDiv(calcMonths, 12));
880 int newMonth = Math.floorMod(calcMonths, 12) + 1;
881 return with(newYear, newMonth);
882 }
883
884 //-----------------------------------------------------------------------
885 /**
886 * Returns a copy of this year-month with the specified amount subtracted.
887 * <p>
888 * This returns a {@code YearMonth}, based on this one, with the specified amount subtracted.
889 * The amount is typically {@link Period} but may be any other type implementing
890 * the {@link TemporalAmount} interface.
891 * <p>
892 * The calculation is delegated to the amount object by calling
893 * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
894 * to implement the subtraction in any way it wishes, however it typically
895 * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
896 * of the amount implementation to determine if it can be successfully subtracted.
897 * <p>
898 * This instance is immutable and unaffected by this method call.
899 *
900 * @param amountToSubtract the amount to subtract, not null
901 * @return a {@code YearMonth} based on this year-month with the subtraction made, not null
902 * @throws DateTimeException if the subtraction cannot be made
903 * @throws ArithmeticException if numeric overflow occurs
904 */
905 @Override
906 public YearMonth minus(TemporalAmount amountToSubtract) {
907 return (YearMonth) amountToSubtract.subtractFrom(this);
908 }
909
910 /**
911 * Returns a copy of this year-month with the specified amount subtracted.
912 * <p>
913 * This returns a {@code YearMonth}, based on this one, with the amount
914 * in terms of the unit subtracted. If it is not possible to subtract the amount,
915 * because the unit is not supported or for some other reason, an exception is thrown.
916 * <p>
917 * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
918 * See that method for a full description of how addition, and thus subtraction, works.
919 * <p>
920 * This instance is immutable and unaffected by this method call.
921 *
922 * @param amountToSubtract the amount of the unit to subtract from the result, may be negative
923 * @param unit the unit of the amount to subtract, not null
924 * @return a {@code YearMonth} based on this year-month with the specified amount subtracted, not null
925 * @throws DateTimeException if the subtraction cannot be made
926 * @throws UnsupportedTemporalTypeException if the unit is not supported
927 * @throws ArithmeticException if numeric overflow occurs
928 */
929 @Override
930 public YearMonth minus(long amountToSubtract, TemporalUnit unit) {
931 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
932 }
933
934 /**
935 * Returns a copy of this {@code YearMonth} with the specified number of years subtracted.
936 * <p>
937 * This instance is immutable and unaffected by this method call.
938 *
939 * @param yearsToSubtract the years to subtract, may be negative
940 * @return a {@code YearMonth} based on this year-month with the years subtracted, not null
941 * @throws DateTimeException if the result exceeds the supported range
942 */
943 public YearMonth minusYears(long yearsToSubtract) {
944 return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
945 }
946
947 /**
948 * Returns a copy of this {@code YearMonth} with the specified number of months subtracted.
949 * <p>
950 * This instance is immutable and unaffected by this method call.
951 *
952 * @param monthsToSubtract the months to subtract, may be negative
953 * @return a {@code YearMonth} based on this year-month with the months subtracted, not null
954 * @throws DateTimeException if the result exceeds the supported range
955 */
956 public YearMonth minusMonths(long monthsToSubtract) {
957 return (monthsToSubtract == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-monthsToSubtract));
958 }
959
960 //-----------------------------------------------------------------------
961 /**
962 * Queries this year-month using the specified query.
963 * <p>
964 * This queries this year-month using the specified query strategy object.
965 * The {@code TemporalQuery} object defines the logic to be used to
966 * obtain the result. Read the documentation of the query to understand
967 * what the result of this method will be.
968 * <p>
969 * The result of this method is obtained by invoking the
970 * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
971 * specified query passing {@code this} as the argument.
972 *
973 * @param <R> the type of the result
974 * @param query the query to invoke, not null
975 * @return the query result, null may be returned (defined by the query)
976 * @throws DateTimeException if unable to query (defined by the query)
977 * @throws ArithmeticException if numeric overflow occurs (defined by the query)
978 */
979 @SuppressWarnings("unchecked")
980 @Override
981 public <R> R query(TemporalQuery<R> query) {
982 if (query == TemporalQueries.chronology()) {
983 return (R) IsoChronology.INSTANCE;
984 } else if (query == TemporalQueries.precision()) {
985 return (R) MONTHS;
986 }
987 return Temporal.super.query(query);
988 }
989
990 /**
991 * Adjusts the specified temporal object to have this year-month.
992 * <p>
993 * This returns a temporal object of the same observable type as the input
994 * with the year and month changed to be the same as this.
995 * <p>
996 * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
997 * passing {@link ChronoField#PROLEPTIC_MONTH} as the field.
998 * If the specified temporal object does not use the ISO calendar system then
999 * a {@code DateTimeException} is thrown.
1000 * <p>
1001 * In most cases, it is clearer to reverse the calling pattern by using
1002 * {@link Temporal#with(TemporalAdjuster)}:
1003 * <pre>
1004 * // these two lines are equivalent, but the second approach is recommended
1005 * temporal = thisYearMonth.adjustInto(temporal);
1006 * temporal = temporal.with(thisYearMonth);
1007 * </pre>
1008 * <p>
1009 * This instance is immutable and unaffected by this method call.
1010 *
1011 * @param temporal the target object to be adjusted, not null
1012 * @return the adjusted object, not null
1013 * @throws DateTimeException if unable to make the adjustment
1014 * @throws ArithmeticException if numeric overflow occurs
1015 */
1016 @Override
1017 public Temporal adjustInto(Temporal temporal) {
1018 if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
1019 throw new DateTimeException("Adjustment only supported on ISO date-time");
1020 }
1021 return temporal.with(PROLEPTIC_MONTH, getProlepticMonth());
1022 }
1023
1024 /**
1025 * Calculates the amount of time until another year-month in terms of the specified unit.
1026 * <p>
1027 * This calculates the amount of time between two {@code YearMonth}
1028 * objects in terms of a single {@code TemporalUnit}.
1029 * The start and end points are {@code this} and the specified year-month.
1030 * The result will be negative if the end is before the start.
1031 * The {@code Temporal} passed to this method is converted to a
1032 * {@code YearMonth} using {@link #from(TemporalAccessor)}.
1033 * For example, the amount in years between two year-months can be calculated
1034 * using {@code startYearMonth.until(endYearMonth, YEARS)}.
1035 * <p>
1036 * The calculation returns a whole number, representing the number of
1037 * complete units between the two year-months.
1038 * For example, the amount in decades between 2012-06 and 2032-05
1039 * will only be one decade as it is one month short of two decades.
1040 * <p>
1041 * There are two equivalent ways of using this method.
1042 * The first is to invoke this method.
1043 * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
1044 * <pre>
1045 * // these two lines are equivalent
1046 * amount = start.until(end, MONTHS);
1047 * amount = MONTHS.between(start, end);
1048 * </pre>
1049 * The choice should be made based on which makes the code more readable.
1050 * <p>
1051 * The calculation is implemented in this method for {@link ChronoUnit}.
1052 * The units {@code MONTHS}, {@code YEARS}, {@code DECADES},
1053 * {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported.
1054 * Other {@code ChronoUnit} values will throw an exception.
1055 * <p>
1056 * If the unit is not a {@code ChronoUnit}, then the result of this method
1057 * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
1058 * passing {@code this} as the first argument and the converted input temporal
1059 * as the second argument.
1060 * <p>
1061 * This instance is immutable and unaffected by this method call.
1062 *
1063 * @param endExclusive the end date, exclusive, which is converted to a {@code YearMonth}, not null
1064 * @param unit the unit to measure the amount in, not null
1065 * @return the amount of time between this year-month and the end year-month
1066 * @throws DateTimeException if the amount cannot be calculated, or the end
1067 * temporal cannot be converted to a {@code YearMonth}
1068 * @throws UnsupportedTemporalTypeException if the unit is not supported
1069 * @throws ArithmeticException if numeric overflow occurs
1070 */
1071 @Override
1072 public long until(Temporal endExclusive, TemporalUnit unit) {
1073 YearMonth end = YearMonth.from(endExclusive);
1074 if (unit instanceof ChronoUnit chronoUnit) {
1075 long monthsUntil = end.getProlepticMonth() - getProlepticMonth(); // no overflow
1076 return switch (chronoUnit) {
1077 case MONTHS -> monthsUntil;
1078 case YEARS -> monthsUntil / 12;
1079 case DECADES -> monthsUntil / 120;
1080 case CENTURIES -> monthsUntil / 1200;
1081 case MILLENNIA -> monthsUntil / 12000;
1082 case ERAS -> end.getLong(ERA) - getLong(ERA);
1083 default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
1084 };
1085 }
1086 return unit.between(this, end);
1087 }
1088
1089 /**
1090 * Formats this year-month using the specified formatter.
1091 * <p>
1092 * This year-month will be passed to the formatter to produce a string.
1093 *
1094 * @param formatter the formatter to use, not null
1095 * @return the formatted year-month string, not null
1096 * @throws DateTimeException if an error occurs during printing
1097 */
1098 public String format(DateTimeFormatter formatter) {
1099 Objects.requireNonNull(formatter, "formatter");
1100 return formatter.format(this);
1101 }
1102
1103 //-----------------------------------------------------------------------
1104 /**
1105 * Combines this year-month with a day-of-month to create a {@code LocalDate}.
1106 * <p>
1107 * This returns a {@code LocalDate} formed from this year-month and the specified day-of-month.
1108 * <p>
1109 * The day-of-month value must be valid for the year-month.
1110 * <p>
1111 * This method can be used as part of a chain to produce a date:
1112 * <pre>
1113 * LocalDate date = year.atMonth(month).atDay(day);
1114 * </pre>
1115 *
1116 * @param dayOfMonth the day-of-month to use, from 1 to 31
1117 * @return the date formed from this year-month and the specified day, not null
1118 * @throws DateTimeException if the day is invalid for the year-month
1119 * @see #isValidDay(int)
1120 */
1121 public LocalDate atDay(int dayOfMonth) {
1122 return LocalDate.of(year, month, dayOfMonth);
1123 }
1124
1125 /**
1126 * Returns a {@code LocalDate} at the end of the month.
1127 * <p>
1128 * This returns a {@code LocalDate} based on this year-month.
1129 * The day-of-month is set to the last valid day of the month, taking
1130 * into account leap years.
1131 * <p>
1132 * This method can be used as part of a chain to produce a date:
1133 * <pre>
1134 * LocalDate date = year.atMonth(month).atEndOfMonth();
1135 * </pre>
1136 *
1137 * @return the last valid date of this year-month, not null
1138 */
1139 public LocalDate atEndOfMonth() {
1140 return LocalDate.of(year, month, lengthOfMonth());
1141 }
1142
1143 //-----------------------------------------------------------------------
1144 /**
1145 * Compares this year-month to another year-month.
1146 * <p>
1147 * The comparison is based first on the value of the year, then on the value of the month.
1148 * It is "consistent with equals", as defined by {@link Comparable}.
1149 *
1150 * @param other the other year-month to compare to, not null
1151 * @return the comparator value, that is less than zero if this is before {@code other},
1152 * zero if they are equal, greater than zero if this is after {@code other}
1153 * @see #isBefore
1154 * @see #isAfter
1155 */
1156 @Override
1157 public int compareTo(YearMonth other) {
1158 int cmp = (year - other.year);
1159 if (cmp == 0) {
1160 cmp = (month - other.month);
1161 }
1162 return cmp;
1163 }
1164
1165 /**
1166 * Checks if this year-month is after the specified year-month.
1167 *
1168 * @param other the other year-month to compare to, not null
1169 * @return true if this is after the specified year-month
1170 */
1171 public boolean isAfter(YearMonth other) {
1172 return compareTo(other) > 0;
1173 }
1174
1175 /**
1176 * Checks if this year-month is before the specified year-month.
1177 *
1178 * @param other the other year-month to compare to, not null
1179 * @return true if this point is before the specified year-month
1180 */
1181 public boolean isBefore(YearMonth other) {
1182 return compareTo(other) < 0;
1183 }
1184
1185 //-----------------------------------------------------------------------
1186 /**
1187 * Checks if this year-month is equal to another year-month.
1188 * <p>
1189 * The comparison is based on the time-line position of the year-months.
1190 *
1191 * @param obj the object to check, null returns false
1192 * @return true if this is equal to the other year-month
1193 */
1194 @Override
1195 public boolean equals(Object obj) {
1196 if (this == obj) {
1197 return true;
1198 }
1199 return (obj instanceof YearMonth other)
1200 && year == other.year
1201 && month == other.month;
1202 }
1203
1204 /**
1205 * A hash code for this year-month.
1206 *
1207 * @return a suitable hash code
1208 */
1209 @Override
1210 public int hashCode() {
1211 return year ^ (month << 27);
1212 }
1213
1214 //-----------------------------------------------------------------------
1215 /**
1216 * Outputs this year-month as a {@code String}, such as {@code 2007-12}.
1217 * <p>
1218 * The output will be in the format {@code uuuu-MM}:
1219 *
1220 * @return a string representation of this year-month, not null
1221 */
1222 @Override
1223 public String toString() {
1224 int absYear = Math.abs(year);
1225 StringBuilder buf = new StringBuilder(9);
1226 if (absYear < 10000) {
1227 if (year < 0) {
1228 buf.append('-');
1229 }
1230 DecimalDigits.appendQuad(buf, absYear);
1231 } else {
1232 buf.append(year);
1233 }
1234 buf.append('-');
1235 DecimalDigits.appendPair(buf, month);
1236 return buf.toString();
1237 }
1238
1239 //-----------------------------------------------------------------------
1240 /**
1241 * Writes the object using a
1242 * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1243 * @serialData
1244 * <pre>
1245 * out.writeByte(12); // identifies a YearMonth
1246 * out.writeInt(year);
1247 * out.writeByte(month);
1248 * </pre>
1249 *
1250 * @return the instance of {@code Ser}, not null
1251 */
1252 @java.io.Serial
1253 private Object writeReplace() {
1254 return new Ser(Ser.YEAR_MONTH_TYPE, this);
1255 }
1256
1257 /**
1258 * Defend against malicious streams.
1259 *
1260 * @param s the stream to read
1261 * @throws InvalidObjectException always
1262 */
1263 @java.io.Serial
1264 private void readObject(ObjectInputStream s) throws InvalidObjectException {
1265 throw new InvalidObjectException("Deserialization via serialization delegate");
1266 }
1267
1268 void writeExternal(DataOutput out) throws IOException {
1269 out.writeInt(year);
1270 out.writeByte(month);
1271 }
1272
1273 static YearMonth readExternal(DataInput in) throws IOException {
1274 int year = in.readInt();
1275 byte month = in.readByte();
1276 return YearMonth.of(year, month);
1277 }
1278
1279 }