1 /*
2  * Copyright (c) 2012, 2015, 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     private static final long serialVersionUID = 4183400860270640070L;
132     /**
133      * Parser.
134      */
135     private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
136         .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
137         .appendLiteral('-')
138         .appendValue(MONTH_OF_YEAR, 2)
139         .toFormatter();
140 
141     /**
142      * The year.
143      */
144     private final int year;
145     /**
146      * The month-of-year, not null.
147      */
148     private final int month;
149 
150     //-----------------------------------------------------------------------
151     /**
152      * Obtains the current year-month from the system clock in the default time-zone.
153      * <p>
154      * This will query the {@link Clock#systemDefaultZone() system clock} in the default
155      * time-zone to obtain the current year-month.
156      * <p>
157      * Using this method will prevent the ability to use an alternate clock for testing
158      * because the clock is hard-coded.
159      *
160      * @return the current year-month using the system clock and default time-zone, not null
161      */
now()162     public static YearMonth now() {
163         return now(Clock.systemDefaultZone());
164     }
165 
166     /**
167      * Obtains the current year-month from the system clock in the specified time-zone.
168      * <p>
169      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current year-month.
170      * Specifying the time-zone avoids dependence on the default time-zone.
171      * <p>
172      * Using this method will prevent the ability to use an alternate clock for testing
173      * because the clock is hard-coded.
174      *
175      * @param zone  the zone ID to use, not null
176      * @return the current year-month using the system clock, not null
177      */
now(ZoneId zone)178     public static YearMonth now(ZoneId zone) {
179         return now(Clock.system(zone));
180     }
181 
182     /**
183      * Obtains the current year-month from the specified clock.
184      * <p>
185      * This will query the specified clock to obtain the current year-month.
186      * Using this method allows the use of an alternate clock for testing.
187      * The alternate clock may be introduced using {@link Clock dependency injection}.
188      *
189      * @param clock  the clock to use, not null
190      * @return the current year-month, not null
191      */
now(Clock clock)192     public static YearMonth now(Clock clock) {
193         final LocalDate now = LocalDate.now(clock);  // called once
194         return YearMonth.of(now.getYear(), now.getMonth());
195     }
196 
197     //-----------------------------------------------------------------------
198     /**
199      * Obtains an instance of {@code YearMonth} from a year and month.
200      *
201      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
202      * @param month  the month-of-year to represent, not null
203      * @return the year-month, not null
204      * @throws DateTimeException if the year value is invalid
205      */
of(int year, Month month)206     public static YearMonth of(int year, Month month) {
207         Objects.requireNonNull(month, "month");
208         return of(year, month.getValue());
209     }
210 
211     /**
212      * Obtains an instance of {@code YearMonth} from a year and month.
213      *
214      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
215      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
216      * @return the year-month, not null
217      * @throws DateTimeException if either field value is invalid
218      */
of(int year, int month)219     public static YearMonth of(int year, int month) {
220         YEAR.checkValidValue(year);
221         MONTH_OF_YEAR.checkValidValue(month);
222         return new YearMonth(year, month);
223     }
224 
225     //-----------------------------------------------------------------------
226     /**
227      * Obtains an instance of {@code YearMonth} from a temporal object.
228      * <p>
229      * This obtains a year-month based on the specified temporal.
230      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
231      * which this factory converts to an instance of {@code YearMonth}.
232      * <p>
233      * The conversion extracts the {@link ChronoField#YEAR YEAR} and
234      * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} fields.
235      * The extraction is only permitted if the temporal object has an ISO
236      * chronology, or can be converted to a {@code LocalDate}.
237      * <p>
238      * This method matches the signature of the functional interface {@link TemporalQuery}
239      * allowing it to be used as a query via method reference, {@code YearMonth::from}.
240      *
241      * @param temporal  the temporal object to convert, not null
242      * @return the year-month, not null
243      * @throws DateTimeException if unable to convert to a {@code YearMonth}
244      */
from(TemporalAccessor temporal)245     public static YearMonth from(TemporalAccessor temporal) {
246         if (temporal instanceof YearMonth) {
247             return (YearMonth) temporal;
248         }
249         Objects.requireNonNull(temporal, "temporal");
250         try {
251             if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
252                 temporal = LocalDate.from(temporal);
253             }
254             return of(temporal.get(YEAR), temporal.get(MONTH_OF_YEAR));
255         } catch (DateTimeException ex) {
256             throw new DateTimeException("Unable to obtain YearMonth from TemporalAccessor: " +
257                     temporal + " of type " + temporal.getClass().getName(), ex);
258         }
259     }
260 
261     //-----------------------------------------------------------------------
262     /**
263      * Obtains an instance of {@code YearMonth} from a text string such as {@code 2007-12}.
264      * <p>
265      * The string must represent a valid year-month.
266      * The format must be {@code uuuu-MM}.
267      * Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.
268      *
269      * @param text  the text to parse such as "2007-12", not null
270      * @return the parsed year-month, not null
271      * @throws DateTimeParseException if the text cannot be parsed
272      */
parse(CharSequence text)273     public static YearMonth parse(CharSequence text) {
274         return parse(text, PARSER);
275     }
276 
277     /**
278      * Obtains an instance of {@code YearMonth} from a text string using a specific formatter.
279      * <p>
280      * The text is parsed using the formatter, returning a year-month.
281      *
282      * @param text  the text to parse, not null
283      * @param formatter  the formatter to use, not null
284      * @return the parsed year-month, not null
285      * @throws DateTimeParseException if the text cannot be parsed
286      */
parse(CharSequence text, DateTimeFormatter formatter)287     public static YearMonth parse(CharSequence text, DateTimeFormatter formatter) {
288         Objects.requireNonNull(formatter, "formatter");
289         return formatter.parse(text, YearMonth::from);
290     }
291 
292     //-----------------------------------------------------------------------
293     /**
294      * Constructor.
295      *
296      * @param year  the year to represent, validated from MIN_YEAR to MAX_YEAR
297      * @param month  the month-of-year to represent, validated from 1 (January) to 12 (December)
298      */
YearMonth(int year, int month)299     private YearMonth(int year, int month) {
300         this.year = year;
301         this.month = month;
302     }
303 
304     /**
305      * Returns a copy of this year-month with the new year and month, checking
306      * to see if a new object is in fact required.
307      *
308      * @param newYear  the year to represent, validated from MIN_YEAR to MAX_YEAR
309      * @param newMonth  the month-of-year to represent, validated not null
310      * @return the year-month, not null
311      */
with(int newYear, int newMonth)312     private YearMonth with(int newYear, int newMonth) {
313         if (year == newYear && month == newMonth) {
314             return this;
315         }
316         return new YearMonth(newYear, newMonth);
317     }
318 
319     //-----------------------------------------------------------------------
320     /**
321      * Checks if the specified field is supported.
322      * <p>
323      * This checks if this year-month can be queried for the specified field.
324      * If false, then calling the {@link #range(TemporalField) range},
325      * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
326      * methods will throw an exception.
327      * <p>
328      * If the field is a {@link ChronoField} then the query is implemented here.
329      * The supported fields are:
330      * <ul>
331      * <li>{@code MONTH_OF_YEAR}
332      * <li>{@code PROLEPTIC_MONTH}
333      * <li>{@code YEAR_OF_ERA}
334      * <li>{@code YEAR}
335      * <li>{@code ERA}
336      * </ul>
337      * All other {@code ChronoField} instances will return false.
338      * <p>
339      * If the field is not a {@code ChronoField}, then the result of this method
340      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
341      * passing {@code this} as the argument.
342      * Whether the field is supported is determined by the field.
343      *
344      * @param field  the field to check, null returns false
345      * @return true if the field is supported on this year-month, false if not
346      */
347     @Override
isSupported(TemporalField field)348     public boolean isSupported(TemporalField field) {
349         if (field instanceof ChronoField) {
350             return field == YEAR || field == MONTH_OF_YEAR ||
351                     field == PROLEPTIC_MONTH || field == YEAR_OF_ERA || field == ERA;
352         }
353         return field != null && field.isSupportedBy(this);
354     }
355 
356     /**
357      * Checks if the specified unit is supported.
358      * <p>
359      * This checks if the specified unit can be added to, or subtracted from, this year-month.
360      * If false, then calling the {@link #plus(long, TemporalUnit)} and
361      * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
362      * <p>
363      * If the unit is a {@link ChronoUnit} then the query is implemented here.
364      * The supported units are:
365      * <ul>
366      * <li>{@code MONTHS}
367      * <li>{@code YEARS}
368      * <li>{@code DECADES}
369      * <li>{@code CENTURIES}
370      * <li>{@code MILLENNIA}
371      * <li>{@code ERAS}
372      * </ul>
373      * All other {@code ChronoUnit} instances will return false.
374      * <p>
375      * If the unit is not a {@code ChronoUnit}, then the result of this method
376      * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
377      * passing {@code this} as the argument.
378      * Whether the unit is supported is determined by the unit.
379      *
380      * @param unit  the unit to check, null returns false
381      * @return true if the unit can be added/subtracted, false if not
382      */
383     @Override
isSupported(TemporalUnit unit)384     public boolean isSupported(TemporalUnit unit) {
385         if (unit instanceof ChronoUnit) {
386             return unit == MONTHS || unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS;
387         }
388         return unit != null && unit.isSupportedBy(this);
389     }
390 
391     //-----------------------------------------------------------------------
392     /**
393      * Gets the range of valid values for the specified field.
394      * <p>
395      * The range object expresses the minimum and maximum valid values for a field.
396      * This year-month is used to enhance the accuracy of the returned range.
397      * If it is not possible to return the range, because the field is not supported
398      * or for some other reason, an exception is thrown.
399      * <p>
400      * If the field is a {@link ChronoField} then the query is implemented here.
401      * The {@link #isSupported(TemporalField) supported fields} will return
402      * appropriate range instances.
403      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
404      * <p>
405      * If the field is not a {@code ChronoField}, then the result of this method
406      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
407      * passing {@code this} as the argument.
408      * Whether the range can be obtained is determined by the field.
409      *
410      * @param field  the field to query the range for, not null
411      * @return the range of valid values for the field, not null
412      * @throws DateTimeException if the range for the field cannot be obtained
413      * @throws UnsupportedTemporalTypeException if the field is not supported
414      */
415     @Override
range(TemporalField field)416     public ValueRange range(TemporalField field) {
417         if (field == YEAR_OF_ERA) {
418             return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));
419         }
420         return Temporal.super.range(field);
421     }
422 
423     /**
424      * Gets the value of the specified field from this year-month as an {@code int}.
425      * <p>
426      * This queries this year-month for the value of the specified field.
427      * The returned value will always be within the valid range of values for the field.
428      * If it is not possible to return the value, because the field is not supported
429      * or for some other reason, an exception is thrown.
430      * <p>
431      * If the field is a {@link ChronoField} then the query is implemented here.
432      * The {@link #isSupported(TemporalField) supported fields} will return valid
433      * values based on this year-month, except {@code PROLEPTIC_MONTH} which is too
434      * large to fit in an {@code int} and throw a {@code DateTimeException}.
435      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
436      * <p>
437      * If the field is not a {@code ChronoField}, then the result of this method
438      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
439      * passing {@code this} as the argument. Whether the value can be obtained,
440      * and what the value represents, is determined by the field.
441      *
442      * @param field  the field to get, not null
443      * @return the value for the field
444      * @throws DateTimeException if a value for the field cannot be obtained or
445      *         the value is outside the range of valid values for the field
446      * @throws UnsupportedTemporalTypeException if the field is not supported or
447      *         the range of values exceeds an {@code int}
448      * @throws ArithmeticException if numeric overflow occurs
449      */
450     @Override  // override for Javadoc
get(TemporalField field)451     public int get(TemporalField field) {
452         return range(field).checkValidIntValue(getLong(field), field);
453     }
454 
455     /**
456      * Gets the value of the specified field from this year-month as a {@code long}.
457      * <p>
458      * This queries this year-month for the value of the specified field.
459      * If it is not possible to return the value, because the field is not supported
460      * or for some other reason, an exception is thrown.
461      * <p>
462      * If the field is a {@link ChronoField} then the query is implemented here.
463      * The {@link #isSupported(TemporalField) supported fields} will return valid
464      * values based on this year-month.
465      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
466      * <p>
467      * If the field is not a {@code ChronoField}, then the result of this method
468      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
469      * passing {@code this} as the argument. Whether the value can be obtained,
470      * and what the value represents, is determined by the field.
471      *
472      * @param field  the field to get, not null
473      * @return the value for the field
474      * @throws DateTimeException if a value for the field cannot be obtained
475      * @throws UnsupportedTemporalTypeException if the field is not supported
476      * @throws ArithmeticException if numeric overflow occurs
477      */
478     @Override
getLong(TemporalField field)479     public long getLong(TemporalField field) {
480         if (field instanceof ChronoField) {
481             switch ((ChronoField) field) {
482                 case MONTH_OF_YEAR: return month;
483                 case PROLEPTIC_MONTH: return getProlepticMonth();
484                 case YEAR_OF_ERA: return (year < 1 ? 1 - year : year);
485                 case YEAR: return year;
486                 case ERA: return (year < 1 ? 0 : 1);
487             }
488             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
489         }
490         return field.getFrom(this);
491     }
492 
getProlepticMonth()493     private long getProlepticMonth() {
494         return (year * 12L + month - 1);
495     }
496 
497     //-----------------------------------------------------------------------
498     /**
499      * Gets the year field.
500      * <p>
501      * This method returns the primitive {@code int} value for the year.
502      * <p>
503      * The year returned by this method is proleptic as per {@code get(YEAR)}.
504      *
505      * @return the year, from MIN_YEAR to MAX_YEAR
506      */
getYear()507     public int getYear() {
508         return year;
509     }
510 
511     /**
512      * Gets the month-of-year field from 1 to 12.
513      * <p>
514      * This method returns the month as an {@code int} from 1 to 12.
515      * Application code is frequently clearer if the enum {@link Month}
516      * is used by calling {@link #getMonth()}.
517      *
518      * @return the month-of-year, from 1 to 12
519      * @see #getMonth()
520      */
getMonthValue()521     public int getMonthValue() {
522         return month;
523     }
524 
525     /**
526      * Gets the month-of-year field using the {@code Month} enum.
527      * <p>
528      * This method returns the enum {@link Month} for the month.
529      * This avoids confusion as to what {@code int} values mean.
530      * If you need access to the primitive {@code int} value then the enum
531      * provides the {@link Month#getValue() int value}.
532      *
533      * @return the month-of-year, not null
534      * @see #getMonthValue()
535      */
getMonth()536     public Month getMonth() {
537         return Month.of(month);
538     }
539 
540     //-----------------------------------------------------------------------
541     /**
542      * Checks if the year is a leap year, according to the ISO proleptic
543      * calendar system rules.
544      * <p>
545      * This method applies the current rules for leap years across the whole time-line.
546      * In general, a year is a leap year if it is divisible by four without
547      * remainder. However, years divisible by 100, are not leap years, with
548      * the exception of years divisible by 400 which are.
549      * <p>
550      * For example, 1904 is a leap year it is divisible by 4.
551      * 1900 was not a leap year as it is divisible by 100, however 2000 was a
552      * leap year as it is divisible by 400.
553      * <p>
554      * The calculation is proleptic - applying the same rules into the far future and far past.
555      * This is historically inaccurate, but is correct for the ISO-8601 standard.
556      *
557      * @return true if the year is leap, false otherwise
558      */
isLeapYear()559     public boolean isLeapYear() {
560         return IsoChronology.INSTANCE.isLeapYear(year);
561     }
562 
563     /**
564      * Checks if the day-of-month is valid for this year-month.
565      * <p>
566      * This method checks whether this year and month and the input day form
567      * a valid date.
568      *
569      * @param dayOfMonth  the day-of-month to validate, from 1 to 31, invalid value returns false
570      * @return true if the day is valid for this year-month
571      */
isValidDay(int dayOfMonth)572     public boolean isValidDay(int dayOfMonth) {
573         return dayOfMonth >= 1 && dayOfMonth <= lengthOfMonth();
574     }
575 
576     /**
577      * Returns the length of the month, taking account of the year.
578      * <p>
579      * This returns the length of the month in days.
580      * For example, a date in January would return 31.
581      *
582      * @return the length of the month in days, from 28 to 31
583      */
lengthOfMonth()584     public int lengthOfMonth() {
585         return getMonth().length(isLeapYear());
586     }
587 
588     /**
589      * Returns the length of the year.
590      * <p>
591      * This returns the length of the year in days, either 365 or 366.
592      *
593      * @return 366 if the year is leap, 365 otherwise
594      */
lengthOfYear()595     public int lengthOfYear() {
596         return (isLeapYear() ? 366 : 365);
597     }
598 
599     //-----------------------------------------------------------------------
600     /**
601      * Returns an adjusted copy of this year-month.
602      * <p>
603      * This returns a {@code YearMonth}, based on this one, with the year-month adjusted.
604      * The adjustment takes place using the specified adjuster strategy object.
605      * Read the documentation of the adjuster to understand what adjustment will be made.
606      * <p>
607      * A simple adjuster might simply set the one of the fields, such as the year field.
608      * A more complex adjuster might set the year-month to the next month that
609      * Halley's comet will pass the Earth.
610      * <p>
611      * The result of this method is obtained by invoking the
612      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
613      * specified adjuster passing {@code this} as the argument.
614      * <p>
615      * This instance is immutable and unaffected by this method call.
616      *
617      * @param adjuster the adjuster to use, not null
618      * @return a {@code YearMonth} based on {@code this} with the adjustment made, not null
619      * @throws DateTimeException if the adjustment cannot be made
620      * @throws ArithmeticException if numeric overflow occurs
621      */
622     @Override
with(TemporalAdjuster adjuster)623     public YearMonth with(TemporalAdjuster adjuster) {
624         return (YearMonth) adjuster.adjustInto(this);
625     }
626 
627     /**
628      * Returns a copy of this year-month with the specified field set to a new value.
629      * <p>
630      * This returns a {@code YearMonth}, based on this one, with the value
631      * for the specified field changed.
632      * This can be used to change any supported field, such as the year or month.
633      * If it is not possible to set the value, because the field is not supported or for
634      * some other reason, an exception is thrown.
635      * <p>
636      * If the field is a {@link ChronoField} then the adjustment is implemented here.
637      * The supported fields behave as follows:
638      * <ul>
639      * <li>{@code MONTH_OF_YEAR} -
640      *  Returns a {@code YearMonth} with the specified month-of-year.
641      *  The year will be unchanged.
642      * <li>{@code PROLEPTIC_MONTH} -
643      *  Returns a {@code YearMonth} with the specified proleptic-month.
644      *  This completely replaces the year and month of this object.
645      * <li>{@code YEAR_OF_ERA} -
646      *  Returns a {@code YearMonth} with the specified year-of-era
647      *  The month and era will be unchanged.
648      * <li>{@code YEAR} -
649      *  Returns a {@code YearMonth} with the specified year.
650      *  The month will be unchanged.
651      * <li>{@code ERA} -
652      *  Returns a {@code YearMonth} with the specified era.
653      *  The month and year-of-era will be unchanged.
654      * </ul>
655      * <p>
656      * In all cases, if the new value is outside the valid range of values for the field
657      * then a {@code DateTimeException} will be thrown.
658      * <p>
659      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
660      * <p>
661      * If the field is not a {@code ChronoField}, then the result of this method
662      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
663      * passing {@code this} as the argument. In this case, the field determines
664      * whether and how to adjust the instant.
665      * <p>
666      * This instance is immutable and unaffected by this method call.
667      *
668      * @param field  the field to set in the result, not null
669      * @param newValue  the new value of the field in the result
670      * @return a {@code YearMonth} based on {@code this} with the specified field set, not null
671      * @throws DateTimeException if the field cannot be set
672      * @throws UnsupportedTemporalTypeException if the field is not supported
673      * @throws ArithmeticException if numeric overflow occurs
674      */
675     @Override
with(TemporalField field, long newValue)676     public YearMonth with(TemporalField field, long newValue) {
677         if (field instanceof ChronoField) {
678             ChronoField f = (ChronoField) field;
679             f.checkValidValue(newValue);
680             switch (f) {
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) {
801             switch ((ChronoUnit) unit) {
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 = (int)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) {
1042             long monthsUntil = end.getProlepticMonth() - getProlepticMonth();  // no overflow
1043             switch ((ChronoUnit) unit) {
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         if (obj instanceof YearMonth) {
1164             YearMonth other = (YearMonth) obj;
1165             return year == other.year && month == other.month;
1166         }
1167         return false;
1168     }
1169 
1170     /**
1171      * A hash code for this year-month.
1172      *
1173      * @return a suitable hash code
1174      */
1175     @Override
hashCode()1176     public int hashCode() {
1177         return year ^ (month << 27);
1178     }
1179 
1180     //-----------------------------------------------------------------------
1181     /**
1182      * Outputs this year-month as a {@code String}, such as {@code 2007-12}.
1183      * <p>
1184      * The output will be in the format {@code uuuu-MM}:
1185      *
1186      * @return a string representation of this year-month, not null
1187      */
1188     @Override
toString()1189     public String toString() {
1190         int absYear = Math.abs(year);
1191         StringBuilder buf = new StringBuilder(9);
1192         if (absYear < 1000) {
1193             if (year < 0) {
1194                 buf.append(year - 10000).deleteCharAt(1);
1195             } else {
1196                 buf.append(year + 10000).deleteCharAt(0);
1197             }
1198         } else {
1199             buf.append(year);
1200         }
1201         return buf.append(month < 10 ? "-0" : "-")
1202             .append(month)
1203             .toString();
1204     }
1205 
1206     //-----------------------------------------------------------------------
1207     /**
1208      * Writes the object using a
1209      * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1210      * @serialData
1211      * <pre>
1212      *  out.writeByte(12);  // identifies a YearMonth
1213      *  out.writeInt(year);
1214      *  out.writeByte(month);
1215      * </pre>
1216      *
1217      * @return the instance of {@code Ser}, not null
1218      */
writeReplace()1219     private Object writeReplace() {
1220         return new Ser(Ser.YEAR_MONTH_TYPE, this);
1221     }
1222 
1223     /**
1224      * Defend against malicious streams.
1225      *
1226      * @param s the stream to read
1227      * @throws InvalidObjectException always
1228      */
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