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