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