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