1 /* 2 * Copyright (c) 2012, 2018, 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.LocalTime.SECONDS_PER_DAY; 65 import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH; 66 import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR; 67 import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH; 68 import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR; 69 import static java.time.temporal.ChronoField.DAY_OF_MONTH; 70 import static java.time.temporal.ChronoField.DAY_OF_YEAR; 71 import static java.time.temporal.ChronoField.EPOCH_DAY; 72 import static java.time.temporal.ChronoField.ERA; 73 import static java.time.temporal.ChronoField.MONTH_OF_YEAR; 74 import static java.time.temporal.ChronoField.PROLEPTIC_MONTH; 75 import static java.time.temporal.ChronoField.YEAR; 76 77 import java.io.DataInput; 78 import java.io.DataOutput; 79 import java.io.IOException; 80 import java.io.InvalidObjectException; 81 import java.io.ObjectInputStream; 82 import java.io.Serializable; 83 import java.time.chrono.ChronoLocalDate; 84 import java.time.chrono.IsoEra; 85 import java.time.chrono.IsoChronology; 86 import java.time.format.DateTimeFormatter; 87 import java.time.format.DateTimeParseException; 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.time.zone.ZoneOffsetTransition; 101 import java.time.zone.ZoneRules; 102 import java.util.Objects; 103 import java.util.stream.LongStream; 104 import java.util.stream.Stream; 105 106 /** 107 * A date without a time-zone in the ISO-8601 calendar system, 108 * such as {@code 2007-12-03}. 109 * <p> 110 * {@code LocalDate} is an immutable date-time object that represents a date, 111 * often viewed as year-month-day. Other date fields, such as day-of-year, 112 * day-of-week and week-of-year, can also be accessed. 113 * For example, the value "2nd October 2007" can be stored in a {@code LocalDate}. 114 * <p> 115 * This class does not store or represent a time or time-zone. 116 * Instead, it is a description of the date, as used for birthdays. 117 * It cannot represent an instant on the time-line without additional information 118 * such as an offset or time-zone. 119 * <p> 120 * The ISO-8601 calendar system is the modern civil calendar system used today 121 * in most of the world. It is equivalent to the proleptic Gregorian calendar 122 * system, in which today's rules for leap years are applied for all time. 123 * For most applications written today, the ISO-8601 rules are entirely suitable. 124 * However, any application that makes use of historical dates, and requires them 125 * to be accurate will find the ISO-8601 approach unsuitable. 126 * 127 * <p> 128 * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a> 129 * class; use of identity-sensitive operations (including reference equality 130 * ({@code ==}), identity hash code, or synchronization) on instances of 131 * {@code LocalDate} may have unpredictable results and should be avoided. 132 * The {@code equals} method should be used for comparisons. 133 * 134 * @implSpec 135 * This class is immutable and thread-safe. 136 * 137 * @since 1.8 138 */ 139 public final class LocalDate 140 implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable { 141 142 /** 143 * The minimum supported {@code LocalDate}, '-999999999-01-01'. 144 * This could be used by an application as a "far past" date. 145 */ 146 public static final LocalDate MIN = LocalDate.of(Year.MIN_VALUE, 1, 1); 147 /** 148 * The maximum supported {@code LocalDate}, '+999999999-12-31'. 149 * This could be used by an application as a "far future" date. 150 */ 151 public static final LocalDate MAX = LocalDate.of(Year.MAX_VALUE, 12, 31); 152 /** 153 * The epoch year {@code LocalDate}, '1970-01-01'. 154 */ 155 public static final LocalDate EPOCH = LocalDate.of(1970, 1, 1); 156 157 /** 158 * Serialization version. 159 */ 160 @java.io.Serial 161 private static final long serialVersionUID = 2942565459149668126L; 162 /** 163 * The number of days in a 400 year cycle. 164 */ 165 private static final int DAYS_PER_CYCLE = 146097; 166 /** 167 * The number of days from year zero to year 1970. 168 * There are five 400 year cycles from year zero to 2000. 169 * There are 7 leap years from 1970 to 2000. 170 */ 171 static final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); 172 173 /** 174 * The year. 175 */ 176 private final int year; 177 /** 178 * The month-of-year. 179 */ 180 private final short month; 181 /** 182 * The day-of-month. 183 */ 184 private final short day; 185 186 //----------------------------------------------------------------------- 187 /** 188 * Obtains the current date from the system clock in the default time-zone. 189 * <p> 190 * This will query the {@link Clock#systemDefaultZone() system clock} in the default 191 * time-zone to obtain the current date. 192 * <p> 193 * Using this method will prevent the ability to use an alternate clock for testing 194 * because the clock is hard-coded. 195 * 196 * @return the current date using the system clock and default time-zone, not null 197 */ 198 public static LocalDate now() { 199 return now(Clock.systemDefaultZone()); 200 } 201 202 /** 203 * Obtains the current date from the system clock in the specified time-zone. 204 * <p> 205 * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date. 206 * Specifying the time-zone avoids dependence on the default time-zone. 207 * <p> 208 * Using this method will prevent the ability to use an alternate clock for testing 209 * because the clock is hard-coded. 210 * 211 * @param zone the zone ID to use, not null 212 * @return the current date using the system clock, not null 213 */ 214 public static LocalDate now(ZoneId zone) { 215 return now(Clock.system(zone)); 216 } 217 218 /** 219 * Obtains the current date from the specified clock. 220 * <p> 221 * This will query the specified clock to obtain the current date - today. 222 * Using this method allows the use of an alternate clock for testing. 223 * The alternate clock may be introduced using {@link Clock dependency injection}. 224 * 225 * @param clock the clock to use, not null 226 * @return the current date, not null 227 */ 228 public static LocalDate now(Clock clock) { 229 Objects.requireNonNull(clock, "clock"); 230 final Instant now = clock.instant(); // called once 231 return ofInstant(now, clock.getZone()); 232 } 233 234 //----------------------------------------------------------------------- 235 /** 236 * Obtains an instance of {@code LocalDate} from a year, month and day. 237 * <p> 238 * This returns a {@code LocalDate} with the specified year, month and day-of-month. 239 * The day must be valid for the year and month, otherwise an exception will be thrown. 240 * 241 * @param year the year to represent, from MIN_YEAR to MAX_YEAR 242 * @param month the month-of-year to represent, not null 243 * @param dayOfMonth the day-of-month to represent, from 1 to 31 244 * @return the local date, not null 245 * @throws DateTimeException if the value of any field is out of range, 246 * or if the day-of-month is invalid for the month-year 247 */ 248 public static LocalDate of(int year, Month month, int dayOfMonth) { 249 YEAR.checkValidValue(year); 250 Objects.requireNonNull(month, "month"); 251 DAY_OF_MONTH.checkValidValue(dayOfMonth); 252 return create(year, month.getValue(), dayOfMonth); 253 } 254 255 /** 256 * Obtains an instance of {@code LocalDate} from a year, month and day. 257 * <p> 258 * This returns a {@code LocalDate} with the specified year, month and day-of-month. 259 * The day must be valid for the year and month, otherwise an exception will be thrown. 260 * 261 * @param year the year to represent, from MIN_YEAR to MAX_YEAR 262 * @param month the month-of-year to represent, from 1 (January) to 12 (December) 263 * @param dayOfMonth the day-of-month to represent, from 1 to 31 264 * @return the local date, not null 265 * @throws DateTimeException if the value of any field is out of range, 266 * or if the day-of-month is invalid for the month-year 267 */ 268 public static LocalDate of(int year, int month, int dayOfMonth) { 269 YEAR.checkValidValue(year); 270 MONTH_OF_YEAR.checkValidValue(month); 271 DAY_OF_MONTH.checkValidValue(dayOfMonth); 272 return create(year, month, dayOfMonth); 273 } 274 275 //----------------------------------------------------------------------- 276 /** 277 * Obtains an instance of {@code LocalDate} from a year and day-of-year. 278 * <p> 279 * This returns a {@code LocalDate} with the specified year and day-of-year. 280 * The day-of-year must be valid for the year, otherwise an exception will be thrown. 281 * 282 * @param year the year to represent, from MIN_YEAR to MAX_YEAR 283 * @param dayOfYear the day-of-year to represent, from 1 to 366 284 * @return the local date, not null 285 * @throws DateTimeException if the value of any field is out of range, 286 * or if the day-of-year is invalid for the year 287 */ 288 public static LocalDate ofYearDay(int year, int dayOfYear) { 289 YEAR.checkValidValue(year); 290 DAY_OF_YEAR.checkValidValue(dayOfYear); 291 boolean leap = IsoChronology.INSTANCE.isLeapYear(year); 292 if (dayOfYear == 366 && leap == false) { 293 throw new DateTimeException("Invalid date 'DayOfYear 366' as '" + year + "' is not a leap year"); 294 } 295 Month moy = Month.of((dayOfYear - 1) / 31 + 1); 296 int monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1; 297 if (dayOfYear > monthEnd) { 298 moy = moy.plus(1); 299 } 300 int dom = dayOfYear - moy.firstDayOfYear(leap) + 1; 301 return new LocalDate(year, moy.getValue(), dom); 302 } 303 304 //----------------------------------------------------------------------- 305 /** 306 * Obtains an instance of {@code LocalDate} from an {@code Instant} and zone ID. 307 * <p> 308 * This creates a local date based on the specified instant. 309 * First, the offset from UTC/Greenwich is obtained using the zone ID and instant, 310 * which is simple as there is only one valid offset for each instant. 311 * Then, the instant and offset are used to calculate the local date. 312 * 313 * @param instant the instant to create the date from, not null 314 * @param zone the time-zone, which may be an offset, not null 315 * @return the local date, not null 316 * @throws DateTimeException if the result exceeds the supported range 317 * @since 9 318 */ 319 public static LocalDate ofInstant(Instant instant, ZoneId zone) { 320 Objects.requireNonNull(instant, "instant"); 321 Objects.requireNonNull(zone, "zone"); 322 ZoneRules rules = zone.getRules(); 323 ZoneOffset offset = rules.getOffset(instant); 324 long localSecond = instant.getEpochSecond() + offset.getTotalSeconds(); 325 long localEpochDay = Math.floorDiv(localSecond, SECONDS_PER_DAY); 326 return ofEpochDay(localEpochDay); 327 } 328 329 //----------------------------------------------------------------------- 330 /** 331 * Obtains an instance of {@code LocalDate} from the epoch day count. 332 * <p> 333 * This returns a {@code LocalDate} with the specified epoch-day. 334 * The {@link ChronoField#EPOCH_DAY EPOCH_DAY} is a simple incrementing count 335 * of days where day 0 is 1970-01-01. Negative numbers represent earlier days. 336 * 337 * @param epochDay the Epoch Day to convert, based on the epoch 1970-01-01 338 * @return the local date, not null 339 * @throws DateTimeException if the epoch day exceeds the supported date range 340 */ 341 public static LocalDate ofEpochDay(long epochDay) { 342 EPOCH_DAY.checkValidValue(epochDay); 343 long zeroDay = epochDay + DAYS_0000_TO_1970; 344 // find the march-based year 345 zeroDay -= 60; // adjust to 0000-03-01 so leap day is at end of four year cycle 346 long adjust = 0; 347 if (zeroDay < 0) { 348 // adjust negative years to positive for calculation 349 long adjustCycles = (zeroDay + 1) / DAYS_PER_CYCLE - 1; 350 adjust = adjustCycles * 400; 351 zeroDay += -adjustCycles * DAYS_PER_CYCLE; 352 } 353 long yearEst = (400 * zeroDay + 591) / DAYS_PER_CYCLE; 354 long doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400); 355 if (doyEst < 0) { 356 // fix estimate 357 yearEst--; 358 doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400); 359 } 360 yearEst += adjust; // reset any negative year 361 int marchDoy0 = (int) doyEst; 362 363 // convert march-based values back to january-based 364 int marchMonth0 = (marchDoy0 * 5 + 2) / 153; 365 int month = (marchMonth0 + 2) % 12 + 1; 366 int dom = marchDoy0 - (marchMonth0 * 306 + 5) / 10 + 1; 367 yearEst += marchMonth0 / 10; 368 369 // check year now we are certain it is correct 370 int year = YEAR.checkValidIntValue(yearEst); 371 return new LocalDate(year, month, dom); 372 } 373 374 //----------------------------------------------------------------------- 375 /** 376 * Obtains an instance of {@code LocalDate} from a temporal object. 377 * <p> 378 * This obtains a local date based on the specified temporal. 379 * A {@code TemporalAccessor} represents an arbitrary set of date and time information, 380 * which this factory converts to an instance of {@code LocalDate}. 381 * <p> 382 * The conversion uses the {@link TemporalQueries#localDate()} query, which relies 383 * on extracting the {@link ChronoField#EPOCH_DAY EPOCH_DAY} field. 384 * <p> 385 * This method matches the signature of the functional interface {@link TemporalQuery} 386 * allowing it to be used as a query via method reference, {@code LocalDate::from}. 387 * 388 * @param temporal the temporal object to convert, not null 389 * @return the local date, not null 390 * @throws DateTimeException if unable to convert to a {@code LocalDate} 391 */ 392 public static LocalDate from(TemporalAccessor temporal) { 393 Objects.requireNonNull(temporal, "temporal"); 394 LocalDate date = temporal.query(TemporalQueries.localDate()); 395 if (date == null) { 396 throw new DateTimeException("Unable to obtain LocalDate from TemporalAccessor: " + 397 temporal + " of type " + temporal.getClass().getName()); 398 } 399 return date; 400 } 401 402 //----------------------------------------------------------------------- 403 /** 404 * Obtains an instance of {@code LocalDate} from a text string such as {@code 2007-12-03}. 405 * <p> 406 * The string must represent a valid date and is parsed using 407 * {@link java.time.format.DateTimeFormatter#ISO_LOCAL_DATE}. 408 * 409 * @param text the text to parse such as "2007-12-03", not null 410 * @return the parsed local date, not null 411 * @throws DateTimeParseException if the text cannot be parsed 412 */ 413 public static LocalDate parse(CharSequence text) { 414 return parse(text, DateTimeFormatter.ISO_LOCAL_DATE); 415 } 416 417 /** 418 * Obtains an instance of {@code LocalDate} from a text string using a specific formatter. 419 * <p> 420 * The text is parsed using the formatter, returning a date. 421 * 422 * @param text the text to parse, not null 423 * @param formatter the formatter to use, not null 424 * @return the parsed local date, not null 425 * @throws DateTimeParseException if the text cannot be parsed 426 */ 427 public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) { 428 Objects.requireNonNull(formatter, "formatter"); 429 return formatter.parse(text, LocalDate::from); 430 } 431 432 //----------------------------------------------------------------------- 433 /** 434 * Creates a local date from the year, month and day fields. 435 * 436 * @param year the year to represent, validated from MIN_YEAR to MAX_YEAR 437 * @param month the month-of-year to represent, from 1 to 12, validated 438 * @param dayOfMonth the day-of-month to represent, validated from 1 to 31 439 * @return the local date, not null 440 * @throws DateTimeException if the day-of-month is invalid for the month-year 441 */ 442 private static LocalDate create(int year, int month, int dayOfMonth) { 443 if (dayOfMonth > 28) { 444 int dom = 31; 445 switch (month) { 446 case 2: 447 dom = (IsoChronology.INSTANCE.isLeapYear(year) ? 29 : 28); 448 break; 449 case 4: 450 case 6: 451 case 9: 452 case 11: 453 dom = 30; 454 break; 455 } 456 if (dayOfMonth > dom) { 457 if (dayOfMonth == 29) { 458 throw new DateTimeException("Invalid date 'February 29' as '" + year + "' is not a leap year"); 459 } else { 460 throw new DateTimeException("Invalid date '" + Month.of(month).name() + " " + dayOfMonth + "'"); 461 } 462 } 463 } 464 return new LocalDate(year, month, dayOfMonth); 465 } 466 467 /** 468 * Resolves the date, resolving days past the end of month. 469 * 470 * @param year the year to represent, validated from MIN_YEAR to MAX_YEAR 471 * @param month the month-of-year to represent, validated from 1 to 12 472 * @param day the day-of-month to represent, validated from 1 to 31 473 * @return the resolved date, not null 474 */ 475 private static LocalDate resolvePreviousValid(int year, int month, int day) { 476 switch (month) { 477 case 2: 478 day = Math.min(day, IsoChronology.INSTANCE.isLeapYear(year) ? 29 : 28); 479 break; 480 case 4: 481 case 6: 482 case 9: 483 case 11: 484 day = Math.min(day, 30); 485 break; 486 } 487 return new LocalDate(year, month, day); 488 } 489 490 /** 491 * Constructor, previously validated. 492 * 493 * @param year the year to represent, from MIN_YEAR to MAX_YEAR 494 * @param month the month-of-year to represent, not null 495 * @param dayOfMonth the day-of-month to represent, valid for year-month, from 1 to 31 496 */ 497 private LocalDate(int year, int month, int dayOfMonth) { 498 this.year = year; 499 this.month = (short) month; 500 this.day = (short) dayOfMonth; 501 } 502 503 //----------------------------------------------------------------------- 504 /** 505 * Checks if the specified field is supported. 506 * <p> 507 * This checks if this date can be queried for the specified field. 508 * If false, then calling the {@link #range(TemporalField) range}, 509 * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)} 510 * methods will throw an exception. 511 * <p> 512 * If the field is a {@link ChronoField} then the query is implemented here. 513 * The supported fields are: 514 * <ul> 515 * <li>{@code DAY_OF_WEEK} 516 * <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH} 517 * <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR} 518 * <li>{@code DAY_OF_MONTH} 519 * <li>{@code DAY_OF_YEAR} 520 * <li>{@code EPOCH_DAY} 521 * <li>{@code ALIGNED_WEEK_OF_MONTH} 522 * <li>{@code ALIGNED_WEEK_OF_YEAR} 523 * <li>{@code MONTH_OF_YEAR} 524 * <li>{@code PROLEPTIC_MONTH} 525 * <li>{@code YEAR_OF_ERA} 526 * <li>{@code YEAR} 527 * <li>{@code ERA} 528 * </ul> 529 * All other {@code ChronoField} instances will return false. 530 * <p> 531 * If the field is not a {@code ChronoField}, then the result of this method 532 * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)} 533 * passing {@code this} as the argument. 534 * Whether the field is supported is determined by the field. 535 * 536 * @param field the field to check, null returns false 537 * @return true if the field is supported on this date, false if not 538 */ 539 @Override // override for Javadoc 540 public boolean isSupported(TemporalField field) { 541 return ChronoLocalDate.super.isSupported(field); 542 } 543 544 /** 545 * Checks if the specified unit is supported. 546 * <p> 547 * This checks if the specified unit can be added to, or subtracted from, this date. 548 * If false, then calling the {@link #plus(long, TemporalUnit)} and 549 * {@link #minus(long, TemporalUnit) minus} methods will throw an exception. 550 * <p> 551 * If the unit is a {@link ChronoUnit} then the query is implemented here. 552 * The supported units are: 553 * <ul> 554 * <li>{@code DAYS} 555 * <li>{@code WEEKS} 556 * <li>{@code MONTHS} 557 * <li>{@code YEARS} 558 * <li>{@code DECADES} 559 * <li>{@code CENTURIES} 560 * <li>{@code MILLENNIA} 561 * <li>{@code ERAS} 562 * </ul> 563 * All other {@code ChronoUnit} instances will return false. 564 * <p> 565 * If the unit is not a {@code ChronoUnit}, then the result of this method 566 * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)} 567 * passing {@code this} as the argument. 568 * Whether the unit is supported is determined by the unit. 569 * 570 * @param unit the unit to check, null returns false 571 * @return true if the unit can be added/subtracted, false if not 572 */ 573 @Override // override for Javadoc 574 public boolean isSupported(TemporalUnit unit) { 575 return ChronoLocalDate.super.isSupported(unit); 576 } 577 578 //----------------------------------------------------------------------- 579 /** 580 * Gets the range of valid values for the specified field. 581 * <p> 582 * The range object expresses the minimum and maximum valid values for a field. 583 * This date is used to enhance the accuracy of the returned range. 584 * If it is not possible to return the range, because the field is not supported 585 * or for some other reason, an exception is thrown. 586 * <p> 587 * If the field is a {@link ChronoField} then the query is implemented here. 588 * The {@link #isSupported(TemporalField) supported fields} will return 589 * appropriate range instances. 590 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 591 * <p> 592 * If the field is not a {@code ChronoField}, then the result of this method 593 * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)} 594 * passing {@code this} as the argument. 595 * Whether the range can be obtained is determined by the field. 596 * 597 * @param field the field to query the range for, not null 598 * @return the range of valid values for the field, not null 599 * @throws DateTimeException if the range for the field cannot be obtained 600 * @throws UnsupportedTemporalTypeException if the field is not supported 601 */ 602 @Override 603 public ValueRange range(TemporalField field) { 604 if (field instanceof ChronoField) { 605 ChronoField f = (ChronoField) field; 606 if (f.isDateBased()) { 607 switch (f) { 608 case DAY_OF_MONTH: return ValueRange.of(1, lengthOfMonth()); 609 case DAY_OF_YEAR: return ValueRange.of(1, lengthOfYear()); 610 case ALIGNED_WEEK_OF_MONTH: return ValueRange.of(1, getMonth() == Month.FEBRUARY && isLeapYear() == false ? 4 : 5); 611 case YEAR_OF_ERA: 612 return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE)); 613 } 614 return field.range(); 615 } 616 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 617 } 618 return field.rangeRefinedBy(this); 619 } 620 621 /** 622 * Gets the value of the specified field from this date as an {@code int}. 623 * <p> 624 * This queries this date for the value of the specified field. 625 * The returned value will always be within the valid range of values for the field. 626 * If it is not possible to return the value, because the field is not supported 627 * or for some other reason, an exception is thrown. 628 * <p> 629 * If the field is a {@link ChronoField} then the query is implemented here. 630 * The {@link #isSupported(TemporalField) supported fields} will return valid 631 * values based on this date, except {@code EPOCH_DAY} and {@code PROLEPTIC_MONTH} 632 * which are too large to fit in an {@code int} and throw an {@code UnsupportedTemporalTypeException}. 633 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 634 * <p> 635 * If the field is not a {@code ChronoField}, then the result of this method 636 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 637 * passing {@code this} as the argument. Whether the value can be obtained, 638 * and what the value represents, is determined by the field. 639 * 640 * @param field the field to get, not null 641 * @return the value for the field 642 * @throws DateTimeException if a value for the field cannot be obtained or 643 * the value is outside the range of valid values for the field 644 * @throws UnsupportedTemporalTypeException if the field is not supported or 645 * the range of values exceeds an {@code int} 646 * @throws ArithmeticException if numeric overflow occurs 647 */ 648 @Override // override for Javadoc and performance 649 public int get(TemporalField field) { 650 if (field instanceof ChronoField) { 651 return get0(field); 652 } 653 return ChronoLocalDate.super.get(field); 654 } 655 656 /** 657 * Gets the value of the specified field from this date as a {@code long}. 658 * <p> 659 * This queries this date for the value of the specified field. 660 * If it is not possible to return the value, because the field is not supported 661 * or for some other reason, an exception is thrown. 662 * <p> 663 * If the field is a {@link ChronoField} then the query is implemented here. 664 * The {@link #isSupported(TemporalField) supported fields} will return valid 665 * values based on this date. 666 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 667 * <p> 668 * If the field is not a {@code ChronoField}, then the result of this method 669 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 670 * passing {@code this} as the argument. Whether the value can be obtained, 671 * and what the value represents, is determined by the field. 672 * 673 * @param field the field to get, not null 674 * @return the value for the field 675 * @throws DateTimeException if a value for the field cannot be obtained 676 * @throws UnsupportedTemporalTypeException if the field is not supported 677 * @throws ArithmeticException if numeric overflow occurs 678 */ 679 @Override 680 public long getLong(TemporalField field) { 681 if (field instanceof ChronoField) { 682 if (field == EPOCH_DAY) { 683 return toEpochDay(); 684 } 685 if (field == PROLEPTIC_MONTH) { 686 return getProlepticMonth(); 687 } 688 return get0(field); 689 } 690 return field.getFrom(this); 691 } 692 693 private int get0(TemporalField field) { 694 switch ((ChronoField) field) { 695 case DAY_OF_WEEK: return getDayOfWeek().getValue(); 696 case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((day - 1) % 7) + 1; 697 case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((getDayOfYear() - 1) % 7) + 1; 698 case DAY_OF_MONTH: return day; 699 case DAY_OF_YEAR: return getDayOfYear(); 700 case EPOCH_DAY: throw new UnsupportedTemporalTypeException("Invalid field 'EpochDay' for get() method, use getLong() instead"); 701 case ALIGNED_WEEK_OF_MONTH: return ((day - 1) / 7) + 1; 702 case ALIGNED_WEEK_OF_YEAR: return ((getDayOfYear() - 1) / 7) + 1; 703 case MONTH_OF_YEAR: return month; 704 case PROLEPTIC_MONTH: throw new UnsupportedTemporalTypeException("Invalid field 'ProlepticMonth' for get() method, use getLong() instead"); 705 case YEAR_OF_ERA: return (year >= 1 ? year : 1 - year); 706 case YEAR: return year; 707 case ERA: return (year >= 1 ? 1 : 0); 708 } 709 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 710 } 711 712 private long getProlepticMonth() { 713 return (year * 12L + month - 1); 714 } 715 716 //----------------------------------------------------------------------- 717 /** 718 * Gets the chronology of this date, which is the ISO calendar system. 719 * <p> 720 * The {@code Chronology} represents the calendar system in use. 721 * The ISO-8601 calendar system is the modern civil calendar system used today 722 * in most of the world. It is equivalent to the proleptic Gregorian calendar 723 * system, in which today's rules for leap years are applied for all time. 724 * 725 * @return the ISO chronology, not null 726 */ 727 @Override 728 public IsoChronology getChronology() { 729 return IsoChronology.INSTANCE; 730 } 731 732 /** 733 * Gets the era applicable at this date. 734 * <p> 735 * The official ISO-8601 standard does not define eras, however {@code IsoChronology} does. 736 * It defines two eras, 'CE' from year one onwards and 'BCE' from year zero backwards. 737 * Since dates before the Julian-Gregorian cutover are not in line with history, 738 * the cutover between 'BCE' and 'CE' is also not aligned with the commonly used 739 * eras, often referred to using 'BC' and 'AD'. 740 * <p> 741 * Users of this class should typically ignore this method as it exists primarily 742 * to fulfill the {@link ChronoLocalDate} contract where it is necessary to support 743 * the Japanese calendar system. 744 * 745 * @return the IsoEra applicable at this date, not null 746 */ 747 @Override // override for Javadoc 748 public IsoEra getEra() { 749 return (getYear() >= 1 ? IsoEra.CE : IsoEra.BCE); 750 } 751 752 /** 753 * Gets the year field. 754 * <p> 755 * This method returns the primitive {@code int} value for the year. 756 * <p> 757 * The year returned by this method is proleptic as per {@code get(YEAR)}. 758 * To obtain the year-of-era, use {@code get(YEAR_OF_ERA)}. 759 * 760 * @return the year, from MIN_YEAR to MAX_YEAR 761 */ 762 public int getYear() { 763 return year; 764 } 765 766 /** 767 * Gets the month-of-year field from 1 to 12. 768 * <p> 769 * This method returns the month as an {@code int} from 1 to 12. 770 * Application code is frequently clearer if the enum {@link Month} 771 * is used by calling {@link #getMonth()}. 772 * 773 * @return the month-of-year, from 1 to 12 774 * @see #getMonth() 775 */ 776 public int getMonthValue() { 777 return month; 778 } 779 780 /** 781 * Gets the month-of-year field using the {@code Month} enum. 782 * <p> 783 * This method returns the enum {@link Month} for the month. 784 * This avoids confusion as to what {@code int} values mean. 785 * If you need access to the primitive {@code int} value then the enum 786 * provides the {@link Month#getValue() int value}. 787 * 788 * @return the month-of-year, not null 789 * @see #getMonthValue() 790 */ 791 public Month getMonth() { 792 return Month.of(month); 793 } 794 795 /** 796 * Gets the day-of-month field. 797 * <p> 798 * This method returns the primitive {@code int} value for the day-of-month. 799 * 800 * @return the day-of-month, from 1 to 31 801 */ 802 public int getDayOfMonth() { 803 return day; 804 } 805 806 /** 807 * Gets the day-of-year field. 808 * <p> 809 * This method returns the primitive {@code int} value for the day-of-year. 810 * 811 * @return the day-of-year, from 1 to 365, or 366 in a leap year 812 */ 813 public int getDayOfYear() { 814 return getMonth().firstDayOfYear(isLeapYear()) + day - 1; 815 } 816 817 /** 818 * Gets the day-of-week field, which is an enum {@code DayOfWeek}. 819 * <p> 820 * This method returns the enum {@link DayOfWeek} for the day-of-week. 821 * This avoids confusion as to what {@code int} values mean. 822 * If you need access to the primitive {@code int} value then the enum 823 * provides the {@link DayOfWeek#getValue() int value}. 824 * <p> 825 * Additional information can be obtained from the {@code DayOfWeek}. 826 * This includes textual names of the values. 827 * 828 * @return the day-of-week, not null 829 */ 830 public DayOfWeek getDayOfWeek() { 831 int dow0 = Math.floorMod(toEpochDay() + 3, 7); 832 return DayOfWeek.of(dow0 + 1); 833 } 834 835 //----------------------------------------------------------------------- 836 /** 837 * Checks if the year is a leap year, according to the ISO proleptic 838 * calendar system rules. 839 * <p> 840 * This method applies the current rules for leap years across the whole time-line. 841 * In general, a year is a leap year if it is divisible by four without 842 * remainder. However, years divisible by 100, are not leap years, with 843 * the exception of years divisible by 400 which are. 844 * <p> 845 * For example, 1904 is a leap year it is divisible by 4. 846 * 1900 was not a leap year as it is divisible by 100, however 2000 was a 847 * leap year as it is divisible by 400. 848 * <p> 849 * The calculation is proleptic - applying the same rules into the far future and far past. 850 * This is historically inaccurate, but is correct for the ISO-8601 standard. 851 * 852 * @return true if the year is leap, false otherwise 853 */ 854 @Override // override for Javadoc and performance 855 public boolean isLeapYear() { 856 return IsoChronology.INSTANCE.isLeapYear(year); 857 } 858 859 /** 860 * Returns the length of the month represented by this date. 861 * <p> 862 * This returns the length of the month in days. 863 * For example, a date in January would return 31. 864 * 865 * @return the length of the month in days 866 */ 867 @Override 868 public int lengthOfMonth() { 869 switch (month) { 870 case 2: 871 return (isLeapYear() ? 29 : 28); 872 case 4: 873 case 6: 874 case 9: 875 case 11: 876 return 30; 877 default: 878 return 31; 879 } 880 } 881 882 /** 883 * Returns the length of the year represented by this date. 884 * <p> 885 * This returns the length of the year in days, either 365 or 366. 886 * 887 * @return 366 if the year is leap, 365 otherwise 888 */ 889 @Override // override for Javadoc and performance 890 public int lengthOfYear() { 891 return (isLeapYear() ? 366 : 365); 892 } 893 894 //----------------------------------------------------------------------- 895 /** 896 * Returns an adjusted copy of this date. 897 * <p> 898 * This returns a {@code LocalDate}, based on this one, with the date adjusted. 899 * The adjustment takes place using the specified adjuster strategy object. 900 * Read the documentation of the adjuster to understand what adjustment will be made. 901 * <p> 902 * A simple adjuster might simply set the one of the fields, such as the year field. 903 * A more complex adjuster might set the date to the last day of the month. 904 * <p> 905 * A selection of common adjustments is provided in 906 * {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}. 907 * These include finding the "last day of the month" and "next Wednesday". 908 * Key date-time classes also implement the {@code TemporalAdjuster} interface, 909 * such as {@link Month} and {@link java.time.MonthDay MonthDay}. 910 * The adjuster is responsible for handling special cases, such as the varying 911 * lengths of month and leap years. 912 * <p> 913 * For example this code returns a date on the last day of July: 914 * <pre> 915 * import static java.time.Month.*; 916 * import static java.time.temporal.TemporalAdjusters.*; 917 * 918 * result = localDate.with(JULY).with(lastDayOfMonth()); 919 * </pre> 920 * <p> 921 * The result of this method is obtained by invoking the 922 * {@link TemporalAdjuster#adjustInto(Temporal)} method on the 923 * specified adjuster passing {@code this} as the argument. 924 * <p> 925 * This instance is immutable and unaffected by this method call. 926 * 927 * @param adjuster the adjuster to use, not null 928 * @return a {@code LocalDate} based on {@code this} with the adjustment made, not null 929 * @throws DateTimeException if the adjustment cannot be made 930 * @throws ArithmeticException if numeric overflow occurs 931 */ 932 @Override 933 public LocalDate with(TemporalAdjuster adjuster) { 934 // optimizations 935 if (adjuster instanceof LocalDate) { 936 return (LocalDate) adjuster; 937 } 938 return (LocalDate) adjuster.adjustInto(this); 939 } 940 941 /** 942 * Returns a copy of this date with the specified field set to a new value. 943 * <p> 944 * This returns a {@code LocalDate}, based on this one, with the value 945 * for the specified field changed. 946 * This can be used to change any supported field, such as the year, month or day-of-month. 947 * If it is not possible to set the value, because the field is not supported or for 948 * some other reason, an exception is thrown. 949 * <p> 950 * In some cases, changing the specified field can cause the resulting date to become invalid, 951 * such as changing the month from 31st January to February would make the day-of-month invalid. 952 * In cases like this, the field is responsible for resolving the date. Typically it will choose 953 * the previous valid date, which would be the last valid day of February in this example. 954 * <p> 955 * If the field is a {@link ChronoField} then the adjustment is implemented here. 956 * The supported fields behave as follows: 957 * <ul> 958 * <li>{@code DAY_OF_WEEK} - 959 * Returns a {@code LocalDate} with the specified day-of-week. 960 * The date is adjusted up to 6 days forward or backward within the boundary 961 * of a Monday to Sunday week. 962 * <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH} - 963 * Returns a {@code LocalDate} with the specified aligned-day-of-week. 964 * The date is adjusted to the specified month-based aligned-day-of-week. 965 * Aligned weeks are counted such that the first week of a given month starts 966 * on the first day of that month. 967 * This may cause the date to be moved up to 6 days into the following month. 968 * <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR} - 969 * Returns a {@code LocalDate} with the specified aligned-day-of-week. 970 * The date is adjusted to the specified year-based aligned-day-of-week. 971 * Aligned weeks are counted such that the first week of a given year starts 972 * on the first day of that year. 973 * This may cause the date to be moved up to 6 days into the following year. 974 * <li>{@code DAY_OF_MONTH} - 975 * Returns a {@code LocalDate} with the specified day-of-month. 976 * The month and year will be unchanged. If the day-of-month is invalid for the 977 * year and month, then a {@code DateTimeException} is thrown. 978 * <li>{@code DAY_OF_YEAR} - 979 * Returns a {@code LocalDate} with the specified day-of-year. 980 * The year will be unchanged. If the day-of-year is invalid for the 981 * year, then a {@code DateTimeException} is thrown. 982 * <li>{@code EPOCH_DAY} - 983 * Returns a {@code LocalDate} with the specified epoch-day. 984 * This completely replaces the date and is equivalent to {@link #ofEpochDay(long)}. 985 * <li>{@code ALIGNED_WEEK_OF_MONTH} - 986 * Returns a {@code LocalDate} with the specified aligned-week-of-month. 987 * Aligned weeks are counted such that the first week of a given month starts 988 * on the first day of that month. 989 * This adjustment moves the date in whole week chunks to match the specified week. 990 * The result will have the same day-of-week as this date. 991 * This may cause the date to be moved into the following month. 992 * <li>{@code ALIGNED_WEEK_OF_YEAR} - 993 * Returns a {@code LocalDate} with the specified aligned-week-of-year. 994 * Aligned weeks are counted such that the first week of a given year starts 995 * on the first day of that year. 996 * This adjustment moves the date in whole week chunks to match the specified week. 997 * The result will have the same day-of-week as this date. 998 * This may cause the date to be moved into the following year. 999 * <li>{@code MONTH_OF_YEAR} - 1000 * Returns a {@code LocalDate} with the specified month-of-year. 1001 * The year will be unchanged. The day-of-month will also be unchanged, 1002 * unless it would be invalid for the new month and year. In that case, the 1003 * day-of-month is adjusted to the maximum valid value for the new month and year. 1004 * <li>{@code PROLEPTIC_MONTH} - 1005 * Returns a {@code LocalDate} with the specified proleptic-month. 1006 * The day-of-month will be unchanged, unless it would be invalid for the new month 1007 * and year. In that case, the day-of-month is adjusted to the maximum valid value 1008 * for the new month and year. 1009 * <li>{@code YEAR_OF_ERA} - 1010 * Returns a {@code LocalDate} with the specified year-of-era. 1011 * The era and month will be unchanged. The day-of-month will also be unchanged, 1012 * unless it would be invalid for the new month and year. In that case, the 1013 * day-of-month is adjusted to the maximum valid value for the new month and year. 1014 * <li>{@code YEAR} - 1015 * Returns a {@code LocalDate} with the specified year. 1016 * The month will be unchanged. The day-of-month will also be unchanged, 1017 * unless it would be invalid for the new month and year. In that case, the 1018 * day-of-month is adjusted to the maximum valid value for the new month and year. 1019 * <li>{@code ERA} - 1020 * Returns a {@code LocalDate} with the specified era. 1021 * The year-of-era and month will be unchanged. The day-of-month will also be unchanged, 1022 * unless it would be invalid for the new month and year. In that case, the 1023 * day-of-month is adjusted to the maximum valid value for the new month and year. 1024 * </ul> 1025 * <p> 1026 * In all cases, if the new value is outside the valid range of values for the field 1027 * then a {@code DateTimeException} will be thrown. 1028 * <p> 1029 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 1030 * <p> 1031 * If the field is not a {@code ChronoField}, then the result of this method 1032 * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)} 1033 * passing {@code this} as the argument. In this case, the field determines 1034 * whether and how to adjust the instant. 1035 * <p> 1036 * This instance is immutable and unaffected by this method call. 1037 * 1038 * @param field the field to set in the result, not null 1039 * @param newValue the new value of the field in the result 1040 * @return a {@code LocalDate} based on {@code this} with the specified field set, not null 1041 * @throws DateTimeException if the field cannot be set 1042 * @throws UnsupportedTemporalTypeException if the field is not supported 1043 * @throws ArithmeticException if numeric overflow occurs 1044 */ 1045 @Override 1046 public LocalDate with(TemporalField field, long newValue) { 1047 if (field instanceof ChronoField) { 1048 ChronoField f = (ChronoField) field; 1049 f.checkValidValue(newValue); 1050 switch (f) { 1051 case DAY_OF_WEEK: return plusDays(newValue - getDayOfWeek().getValue()); 1052 case ALIGNED_DAY_OF_WEEK_IN_MONTH: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH)); 1053 case ALIGNED_DAY_OF_WEEK_IN_YEAR: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR)); 1054 case DAY_OF_MONTH: return withDayOfMonth((int) newValue); 1055 case DAY_OF_YEAR: return withDayOfYear((int) newValue); 1056 case EPOCH_DAY: return LocalDate.ofEpochDay(newValue); 1057 case ALIGNED_WEEK_OF_MONTH: return plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_MONTH)); 1058 case ALIGNED_WEEK_OF_YEAR: return plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_YEAR)); 1059 case MONTH_OF_YEAR: return withMonth((int) newValue); 1060 case PROLEPTIC_MONTH: return plusMonths(newValue - getProlepticMonth()); 1061 case YEAR_OF_ERA: return withYear((int) (year >= 1 ? newValue : 1 - newValue)); 1062 case YEAR: return withYear((int) newValue); 1063 case ERA: return (getLong(ERA) == newValue ? this : withYear(1 - year)); 1064 } 1065 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 1066 } 1067 return field.adjustInto(this, newValue); 1068 } 1069 1070 //----------------------------------------------------------------------- 1071 /** 1072 * Returns a copy of this {@code LocalDate} with the year altered. 1073 * <p> 1074 * If the day-of-month is invalid for the year, it will be changed to the last valid day of the month. 1075 * <p> 1076 * This instance is immutable and unaffected by this method call. 1077 * 1078 * @param year the year to set in the result, from MIN_YEAR to MAX_YEAR 1079 * @return a {@code LocalDate} based on this date with the requested year, not null 1080 * @throws DateTimeException if the year value is invalid 1081 */ 1082 public LocalDate withYear(int year) { 1083 if (this.year == year) { 1084 return this; 1085 } 1086 YEAR.checkValidValue(year); 1087 return resolvePreviousValid(year, month, day); 1088 } 1089 1090 /** 1091 * Returns a copy of this {@code LocalDate} with the month-of-year altered. 1092 * <p> 1093 * If the day-of-month is invalid for the year, it will be changed to the last valid day of the month. 1094 * <p> 1095 * This instance is immutable and unaffected by this method call. 1096 * 1097 * @param month the month-of-year to set in the result, from 1 (January) to 12 (December) 1098 * @return a {@code LocalDate} based on this date with the requested month, not null 1099 * @throws DateTimeException if the month-of-year value is invalid 1100 */ 1101 public LocalDate withMonth(int month) { 1102 if (this.month == month) { 1103 return this; 1104 } 1105 MONTH_OF_YEAR.checkValidValue(month); 1106 return resolvePreviousValid(year, month, day); 1107 } 1108 1109 /** 1110 * Returns a copy of this {@code LocalDate} with the day-of-month altered. 1111 * <p> 1112 * If the resulting date is invalid, an exception is thrown. 1113 * <p> 1114 * This instance is immutable and unaffected by this method call. 1115 * 1116 * @param dayOfMonth the day-of-month to set in the result, from 1 to 28-31 1117 * @return a {@code LocalDate} based on this date with the requested day, not null 1118 * @throws DateTimeException if the day-of-month value is invalid, 1119 * or if the day-of-month is invalid for the month-year 1120 */ 1121 public LocalDate withDayOfMonth(int dayOfMonth) { 1122 if (this.day == dayOfMonth) { 1123 return this; 1124 } 1125 return of(year, month, dayOfMonth); 1126 } 1127 1128 /** 1129 * Returns a copy of this {@code LocalDate} with the day-of-year altered. 1130 * <p> 1131 * If the resulting date is invalid, an exception is thrown. 1132 * <p> 1133 * This instance is immutable and unaffected by this method call. 1134 * 1135 * @param dayOfYear the day-of-year to set in the result, from 1 to 365-366 1136 * @return a {@code LocalDate} based on this date with the requested day, not null 1137 * @throws DateTimeException if the day-of-year value is invalid, 1138 * or if the day-of-year is invalid for the year 1139 */ 1140 public LocalDate withDayOfYear(int dayOfYear) { 1141 if (this.getDayOfYear() == dayOfYear) { 1142 return this; 1143 } 1144 return ofYearDay(year, dayOfYear); 1145 } 1146 1147 //----------------------------------------------------------------------- 1148 /** 1149 * Returns a copy of this date with the specified amount added. 1150 * <p> 1151 * This returns a {@code LocalDate}, based on this one, with the specified amount added. 1152 * The amount is typically {@link Period} but may be any other type implementing 1153 * the {@link TemporalAmount} interface. 1154 * <p> 1155 * The calculation is delegated to the amount object by calling 1156 * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free 1157 * to implement the addition in any way it wishes, however it typically 1158 * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation 1159 * of the amount implementation to determine if it can be successfully added. 1160 * <p> 1161 * This instance is immutable and unaffected by this method call. 1162 * 1163 * @param amountToAdd the amount to add, not null 1164 * @return a {@code LocalDate} based on this date with the addition made, not null 1165 * @throws DateTimeException if the addition cannot be made 1166 * @throws ArithmeticException if numeric overflow occurs 1167 */ 1168 @Override 1169 public LocalDate plus(TemporalAmount amountToAdd) { 1170 if (amountToAdd instanceof Period) { 1171 Period periodToAdd = (Period) amountToAdd; 1172 return plusMonths(periodToAdd.toTotalMonths()).plusDays(periodToAdd.getDays()); 1173 } 1174 Objects.requireNonNull(amountToAdd, "amountToAdd"); 1175 return (LocalDate) amountToAdd.addTo(this); 1176 } 1177 1178 /** 1179 * Returns a copy of this date with the specified amount added. 1180 * <p> 1181 * This returns a {@code LocalDate}, based on this one, with the amount 1182 * in terms of the unit added. If it is not possible to add the amount, because the 1183 * unit is not supported or for some other reason, an exception is thrown. 1184 * <p> 1185 * In some cases, adding the amount can cause the resulting date to become invalid. 1186 * For example, adding one month to 31st January would result in 31st February. 1187 * In cases like this, the unit is responsible for resolving the date. 1188 * Typically it will choose the previous valid date, which would be the last valid 1189 * day of February in this example. 1190 * <p> 1191 * If the field is a {@link ChronoUnit} then the addition is implemented here. 1192 * The supported fields behave as follows: 1193 * <ul> 1194 * <li>{@code DAYS} - 1195 * Returns a {@code LocalDate} with the specified number of days added. 1196 * This is equivalent to {@link #plusDays(long)}. 1197 * <li>{@code WEEKS} - 1198 * Returns a {@code LocalDate} with the specified number of weeks added. 1199 * This is equivalent to {@link #plusWeeks(long)} and uses a 7 day week. 1200 * <li>{@code MONTHS} - 1201 * Returns a {@code LocalDate} with the specified number of months added. 1202 * This is equivalent to {@link #plusMonths(long)}. 1203 * The day-of-month will be unchanged unless it would be invalid for the new 1204 * month and year. In that case, the day-of-month is adjusted to the maximum 1205 * valid value for the new month and year. 1206 * <li>{@code YEARS} - 1207 * Returns a {@code LocalDate} with the specified number of years added. 1208 * This is equivalent to {@link #plusYears(long)}. 1209 * The day-of-month will be unchanged unless it would be invalid for the new 1210 * month and year. In that case, the day-of-month is adjusted to the maximum 1211 * valid value for the new month and year. 1212 * <li>{@code DECADES} - 1213 * Returns a {@code LocalDate} with the specified number of decades added. 1214 * This is equivalent to calling {@link #plusYears(long)} with the amount 1215 * multiplied by 10. 1216 * The day-of-month will be unchanged unless it would be invalid for the new 1217 * month and year. In that case, the day-of-month is adjusted to the maximum 1218 * valid value for the new month and year. 1219 * <li>{@code CENTURIES} - 1220 * Returns a {@code LocalDate} with the specified number of centuries added. 1221 * This is equivalent to calling {@link #plusYears(long)} with the amount 1222 * multiplied by 100. 1223 * The day-of-month will be unchanged unless it would be invalid for the new 1224 * month and year. In that case, the day-of-month is adjusted to the maximum 1225 * valid value for the new month and year. 1226 * <li>{@code MILLENNIA} - 1227 * Returns a {@code LocalDate} with the specified number of millennia added. 1228 * This is equivalent to calling {@link #plusYears(long)} with the amount 1229 * multiplied by 1,000. 1230 * The day-of-month will be unchanged unless it would be invalid for the new 1231 * month and year. In that case, the day-of-month is adjusted to the maximum 1232 * valid value for the new month and year. 1233 * <li>{@code ERAS} - 1234 * Returns a {@code LocalDate} with the specified number of eras added. 1235 * Only two eras are supported so the amount must be one, zero or minus one. 1236 * If the amount is non-zero then the year is changed such that the year-of-era 1237 * is unchanged. 1238 * The day-of-month will be unchanged unless it would be invalid for the new 1239 * month and year. In that case, the day-of-month is adjusted to the maximum 1240 * valid value for the new month and year. 1241 * </ul> 1242 * <p> 1243 * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}. 1244 * <p> 1245 * If the field is not a {@code ChronoUnit}, then the result of this method 1246 * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)} 1247 * passing {@code this} as the argument. In this case, the unit determines 1248 * whether and how to perform the addition. 1249 * <p> 1250 * This instance is immutable and unaffected by this method call. 1251 * 1252 * @param amountToAdd the amount of the unit to add to the result, may be negative 1253 * @param unit the unit of the amount to add, not null 1254 * @return a {@code LocalDate} based on this date with the specified amount added, not null 1255 * @throws DateTimeException if the addition cannot be made 1256 * @throws UnsupportedTemporalTypeException if the unit is not supported 1257 * @throws ArithmeticException if numeric overflow occurs 1258 */ 1259 @Override 1260 public LocalDate plus(long amountToAdd, TemporalUnit unit) { 1261 if (unit instanceof ChronoUnit) { 1262 ChronoUnit f = (ChronoUnit) unit; 1263 switch (f) { 1264 case DAYS: return plusDays(amountToAdd); 1265 case WEEKS: return plusWeeks(amountToAdd); 1266 case MONTHS: return plusMonths(amountToAdd); 1267 case YEARS: return plusYears(amountToAdd); 1268 case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10)); 1269 case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100)); 1270 case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000)); 1271 case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd)); 1272 } 1273 throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); 1274 } 1275 return unit.addTo(this, amountToAdd); 1276 } 1277 1278 //----------------------------------------------------------------------- 1279 /** 1280 * Returns a copy of this {@code LocalDate} with the specified number of years added. 1281 * <p> 1282 * This method adds the specified amount to the years field in three steps: 1283 * <ol> 1284 * <li>Add the input years to the year field</li> 1285 * <li>Check if the resulting date would be invalid</li> 1286 * <li>Adjust the day-of-month to the last valid day if necessary</li> 1287 * </ol> 1288 * <p> 1289 * For example, 2008-02-29 (leap year) plus one year would result in the 1290 * invalid date 2009-02-29 (standard year). Instead of returning an invalid 1291 * result, the last valid day of the month, 2009-02-28, is selected instead. 1292 * <p> 1293 * This instance is immutable and unaffected by this method call. 1294 * 1295 * @param yearsToAdd the years to add, may be negative 1296 * @return a {@code LocalDate} based on this date with the years added, not null 1297 * @throws DateTimeException if the result exceeds the supported date range 1298 */ 1299 public LocalDate plusYears(long yearsToAdd) { 1300 if (yearsToAdd == 0) { 1301 return this; 1302 } 1303 int newYear = YEAR.checkValidIntValue(year + yearsToAdd); // safe overflow 1304 return resolvePreviousValid(newYear, month, day); 1305 } 1306 1307 /** 1308 * Returns a copy of this {@code LocalDate} with the specified number of months added. 1309 * <p> 1310 * This method adds the specified amount to the months field in three steps: 1311 * <ol> 1312 * <li>Add the input months to the month-of-year field</li> 1313 * <li>Check if the resulting date would be invalid</li> 1314 * <li>Adjust the day-of-month to the last valid day if necessary</li> 1315 * </ol> 1316 * <p> 1317 * For example, 2007-03-31 plus one month would result in the invalid date 1318 * 2007-04-31. Instead of returning an invalid result, the last valid day 1319 * of the month, 2007-04-30, is selected instead. 1320 * <p> 1321 * This instance is immutable and unaffected by this method call. 1322 * 1323 * @param monthsToAdd the months to add, may be negative 1324 * @return a {@code LocalDate} based on this date with the months added, not null 1325 * @throws DateTimeException if the result exceeds the supported date range 1326 */ 1327 public LocalDate plusMonths(long monthsToAdd) { 1328 if (monthsToAdd == 0) { 1329 return this; 1330 } 1331 long monthCount = year * 12L + (month - 1); 1332 long calcMonths = monthCount + monthsToAdd; // safe overflow 1333 int newYear = YEAR.checkValidIntValue(Math.floorDiv(calcMonths, 12)); 1334 int newMonth = Math.floorMod(calcMonths, 12) + 1; 1335 return resolvePreviousValid(newYear, newMonth, day); 1336 } 1337 1338 /** 1339 * Returns a copy of this {@code LocalDate} with the specified number of weeks added. 1340 * <p> 1341 * This method adds the specified amount in weeks to the days field incrementing 1342 * the month and year fields as necessary to ensure the result remains valid. 1343 * The result is only invalid if the maximum/minimum year is exceeded. 1344 * <p> 1345 * For example, 2008-12-31 plus one week would result in 2009-01-07. 1346 * <p> 1347 * This instance is immutable and unaffected by this method call. 1348 * 1349 * @param weeksToAdd the weeks to add, may be negative 1350 * @return a {@code LocalDate} based on this date with the weeks added, not null 1351 * @throws DateTimeException if the result exceeds the supported date range 1352 */ 1353 public LocalDate plusWeeks(long weeksToAdd) { 1354 return plusDays(Math.multiplyExact(weeksToAdd, 7)); 1355 } 1356 1357 /** 1358 * Returns a copy of this {@code LocalDate} with the specified number of days added. 1359 * <p> 1360 * This method adds the specified amount to the days field incrementing the 1361 * month and year fields as necessary to ensure the result remains valid. 1362 * The result is only invalid if the maximum/minimum year is exceeded. 1363 * <p> 1364 * For example, 2008-12-31 plus one day would result in 2009-01-01. 1365 * <p> 1366 * This instance is immutable and unaffected by this method call. 1367 * 1368 * @param daysToAdd the days to add, may be negative 1369 * @return a {@code LocalDate} based on this date with the days added, not null 1370 * @throws DateTimeException if the result exceeds the supported date range 1371 */ 1372 public LocalDate plusDays(long daysToAdd) { 1373 if (daysToAdd == 0) { 1374 return this; 1375 } 1376 long dom = day + daysToAdd; 1377 if (dom > 0) { 1378 if (dom <= 28) { 1379 return new LocalDate(year, month, (int) dom); 1380 } else if (dom <= 59) { // 59th Jan is 28th Feb, 59th Feb is 31st Mar 1381 long monthLen = lengthOfMonth(); 1382 if (dom <= monthLen) { 1383 return new LocalDate(year, month, (int) dom); 1384 } else if (month < 12) { 1385 return new LocalDate(year, month + 1, (int) (dom - monthLen)); 1386 } else { 1387 YEAR.checkValidValue(year + 1); 1388 return new LocalDate(year + 1, 1, (int) (dom - monthLen)); 1389 } 1390 } 1391 } 1392 1393 long mjDay = Math.addExact(toEpochDay(), daysToAdd); 1394 return LocalDate.ofEpochDay(mjDay); 1395 } 1396 1397 //----------------------------------------------------------------------- 1398 /** 1399 * Returns a copy of this date with the specified amount subtracted. 1400 * <p> 1401 * This returns a {@code LocalDate}, based on this one, with the specified amount subtracted. 1402 * The amount is typically {@link Period} but may be any other type implementing 1403 * the {@link TemporalAmount} interface. 1404 * <p> 1405 * The calculation is delegated to the amount object by calling 1406 * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free 1407 * to implement the subtraction in any way it wishes, however it typically 1408 * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation 1409 * of the amount implementation to determine if it can be successfully subtracted. 1410 * <p> 1411 * This instance is immutable and unaffected by this method call. 1412 * 1413 * @param amountToSubtract the amount to subtract, not null 1414 * @return a {@code LocalDate} based on this date with the subtraction made, not null 1415 * @throws DateTimeException if the subtraction cannot be made 1416 * @throws ArithmeticException if numeric overflow occurs 1417 */ 1418 @Override 1419 public LocalDate minus(TemporalAmount amountToSubtract) { 1420 if (amountToSubtract instanceof Period) { 1421 Period periodToSubtract = (Period) amountToSubtract; 1422 return minusMonths(periodToSubtract.toTotalMonths()).minusDays(periodToSubtract.getDays()); 1423 } 1424 Objects.requireNonNull(amountToSubtract, "amountToSubtract"); 1425 return (LocalDate) amountToSubtract.subtractFrom(this); 1426 } 1427 1428 /** 1429 * Returns a copy of this date with the specified amount subtracted. 1430 * <p> 1431 * This returns a {@code LocalDate}, based on this one, with the amount 1432 * in terms of the unit subtracted. If it is not possible to subtract the amount, 1433 * because the unit is not supported or for some other reason, an exception is thrown. 1434 * <p> 1435 * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated. 1436 * See that method for a full description of how addition, and thus subtraction, works. 1437 * <p> 1438 * This instance is immutable and unaffected by this method call. 1439 * 1440 * @param amountToSubtract the amount of the unit to subtract from the result, may be negative 1441 * @param unit the unit of the amount to subtract, not null 1442 * @return a {@code LocalDate} based on this date with the specified amount subtracted, not null 1443 * @throws DateTimeException if the subtraction cannot be made 1444 * @throws UnsupportedTemporalTypeException if the unit is not supported 1445 * @throws ArithmeticException if numeric overflow occurs 1446 */ 1447 @Override 1448 public LocalDate minus(long amountToSubtract, TemporalUnit unit) { 1449 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); 1450 } 1451 1452 //----------------------------------------------------------------------- 1453 /** 1454 * Returns a copy of this {@code LocalDate} with the specified number of years subtracted. 1455 * <p> 1456 * This method subtracts the specified amount from the years field in three steps: 1457 * <ol> 1458 * <li>Subtract the input years from the year field</li> 1459 * <li>Check if the resulting date would be invalid</li> 1460 * <li>Adjust the day-of-month to the last valid day if necessary</li> 1461 * </ol> 1462 * <p> 1463 * For example, 2008-02-29 (leap year) minus one year would result in the 1464 * invalid date 2007-02-29 (standard year). Instead of returning an invalid 1465 * result, the last valid day of the month, 2007-02-28, is selected instead. 1466 * <p> 1467 * This instance is immutable and unaffected by this method call. 1468 * 1469 * @param yearsToSubtract the years to subtract, may be negative 1470 * @return a {@code LocalDate} based on this date with the years subtracted, not null 1471 * @throws DateTimeException if the result exceeds the supported date range 1472 */ 1473 public LocalDate minusYears(long yearsToSubtract) { 1474 return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract)); 1475 } 1476 1477 /** 1478 * Returns a copy of this {@code LocalDate} with the specified number of months subtracted. 1479 * <p> 1480 * This method subtracts the specified amount from the months field in three steps: 1481 * <ol> 1482 * <li>Subtract the input months from the month-of-year field</li> 1483 * <li>Check if the resulting date would be invalid</li> 1484 * <li>Adjust the day-of-month to the last valid day if necessary</li> 1485 * </ol> 1486 * <p> 1487 * For example, 2007-03-31 minus one month would result in the invalid date 1488 * 2007-02-31. Instead of returning an invalid result, the last valid day 1489 * of the month, 2007-02-28, is selected instead. 1490 * <p> 1491 * This instance is immutable and unaffected by this method call. 1492 * 1493 * @param monthsToSubtract the months to subtract, may be negative 1494 * @return a {@code LocalDate} based on this date with the months subtracted, not null 1495 * @throws DateTimeException if the result exceeds the supported date range 1496 */ 1497 public LocalDate minusMonths(long monthsToSubtract) { 1498 return (monthsToSubtract == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-monthsToSubtract)); 1499 } 1500 1501 /** 1502 * Returns a copy of this {@code LocalDate} with the specified number of weeks subtracted. 1503 * <p> 1504 * This method subtracts the specified amount in weeks from the days field decrementing 1505 * the month and year fields as necessary to ensure the result remains valid. 1506 * The result is only invalid if the maximum/minimum year is exceeded. 1507 * <p> 1508 * For example, 2009-01-07 minus one week would result in 2008-12-31. 1509 * <p> 1510 * This instance is immutable and unaffected by this method call. 1511 * 1512 * @param weeksToSubtract the weeks to subtract, may be negative 1513 * @return a {@code LocalDate} based on this date with the weeks subtracted, not null 1514 * @throws DateTimeException if the result exceeds the supported date range 1515 */ 1516 public LocalDate minusWeeks(long weeksToSubtract) { 1517 return (weeksToSubtract == Long.MIN_VALUE ? plusWeeks(Long.MAX_VALUE).plusWeeks(1) : plusWeeks(-weeksToSubtract)); 1518 } 1519 1520 /** 1521 * Returns a copy of this {@code LocalDate} with the specified number of days subtracted. 1522 * <p> 1523 * This method subtracts the specified amount from the days field decrementing the 1524 * month and year fields as necessary to ensure the result remains valid. 1525 * The result is only invalid if the maximum/minimum year is exceeded. 1526 * <p> 1527 * For example, 2009-01-01 minus one day would result in 2008-12-31. 1528 * <p> 1529 * This instance is immutable and unaffected by this method call. 1530 * 1531 * @param daysToSubtract the days to subtract, may be negative 1532 * @return a {@code LocalDate} based on this date with the days subtracted, not null 1533 * @throws DateTimeException if the result exceeds the supported date range 1534 */ 1535 public LocalDate minusDays(long daysToSubtract) { 1536 return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract)); 1537 } 1538 1539 //----------------------------------------------------------------------- 1540 /** 1541 * Queries this date using the specified query. 1542 * <p> 1543 * This queries this date using the specified query strategy object. 1544 * The {@code TemporalQuery} object defines the logic to be used to 1545 * obtain the result. Read the documentation of the query to understand 1546 * what the result of this method will be. 1547 * <p> 1548 * The result of this method is obtained by invoking the 1549 * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the 1550 * specified query passing {@code this} as the argument. 1551 * 1552 * @param <R> the type of the result 1553 * @param query the query to invoke, not null 1554 * @return the query result, null may be returned (defined by the query) 1555 * @throws DateTimeException if unable to query (defined by the query) 1556 * @throws ArithmeticException if numeric overflow occurs (defined by the query) 1557 */ 1558 @SuppressWarnings("unchecked") 1559 @Override 1560 public <R> R query(TemporalQuery<R> query) { 1561 if (query == TemporalQueries.localDate()) { 1562 return (R) this; 1563 } 1564 return ChronoLocalDate.super.query(query); 1565 } 1566 1567 /** 1568 * Adjusts the specified temporal object to have the same date as this object. 1569 * <p> 1570 * This returns a temporal object of the same observable type as the input 1571 * with the date changed to be the same as this. 1572 * <p> 1573 * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)} 1574 * passing {@link ChronoField#EPOCH_DAY} as the field. 1575 * <p> 1576 * In most cases, it is clearer to reverse the calling pattern by using 1577 * {@link Temporal#with(TemporalAdjuster)}: 1578 * <pre> 1579 * // these two lines are equivalent, but the second approach is recommended 1580 * temporal = thisLocalDate.adjustInto(temporal); 1581 * temporal = temporal.with(thisLocalDate); 1582 * </pre> 1583 * <p> 1584 * This instance is immutable and unaffected by this method call. 1585 * 1586 * @param temporal the target object to be adjusted, not null 1587 * @return the adjusted object, not null 1588 * @throws DateTimeException if unable to make the adjustment 1589 * @throws ArithmeticException if numeric overflow occurs 1590 */ 1591 @Override // override for Javadoc 1592 public Temporal adjustInto(Temporal temporal) { 1593 return ChronoLocalDate.super.adjustInto(temporal); 1594 } 1595 1596 /** 1597 * Calculates the amount of time until another date in terms of the specified unit. 1598 * <p> 1599 * This calculates the amount of time between two {@code LocalDate} 1600 * objects in terms of a single {@code TemporalUnit}. 1601 * The start and end points are {@code this} and the specified date. 1602 * The result will be negative if the end is before the start. 1603 * The {@code Temporal} passed to this method is converted to a 1604 * {@code LocalDate} using {@link #from(TemporalAccessor)}. 1605 * For example, the amount in days between two dates can be calculated 1606 * using {@code startDate.until(endDate, DAYS)}. 1607 * <p> 1608 * The calculation returns a whole number, representing the number of 1609 * complete units between the two dates. 1610 * For example, the amount in months between 2012-06-15 and 2012-08-14 1611 * will only be one month as it is one day short of two months. 1612 * <p> 1613 * There are two equivalent ways of using this method. 1614 * The first is to invoke this method. 1615 * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}: 1616 * <pre> 1617 * // these two lines are equivalent 1618 * amount = start.until(end, MONTHS); 1619 * amount = MONTHS.between(start, end); 1620 * </pre> 1621 * The choice should be made based on which makes the code more readable. 1622 * <p> 1623 * The calculation is implemented in this method for {@link ChronoUnit}. 1624 * The units {@code DAYS}, {@code WEEKS}, {@code MONTHS}, {@code YEARS}, 1625 * {@code DECADES}, {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} 1626 * are supported. Other {@code ChronoUnit} values will throw an exception. 1627 * <p> 1628 * If the unit is not a {@code ChronoUnit}, then the result of this method 1629 * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)} 1630 * passing {@code this} as the first argument and the converted input temporal 1631 * as the second argument. 1632 * <p> 1633 * This instance is immutable and unaffected by this method call. 1634 * 1635 * @param endExclusive the end date, exclusive, which is converted to a {@code LocalDate}, not null 1636 * @param unit the unit to measure the amount in, not null 1637 * @return the amount of time between this date and the end date 1638 * @throws DateTimeException if the amount cannot be calculated, or the end 1639 * temporal cannot be converted to a {@code LocalDate} 1640 * @throws UnsupportedTemporalTypeException if the unit is not supported 1641 * @throws ArithmeticException if numeric overflow occurs 1642 */ 1643 @Override 1644 public long until(Temporal endExclusive, TemporalUnit unit) { 1645 LocalDate end = LocalDate.from(endExclusive); 1646 if (unit instanceof ChronoUnit) { 1647 switch ((ChronoUnit) unit) { 1648 case DAYS: return daysUntil(end); 1649 case WEEKS: return daysUntil(end) / 7; 1650 case MONTHS: return monthsUntil(end); 1651 case YEARS: return monthsUntil(end) / 12; 1652 case DECADES: return monthsUntil(end) / 120; 1653 case CENTURIES: return monthsUntil(end) / 1200; 1654 case MILLENNIA: return monthsUntil(end) / 12000; 1655 case ERAS: return end.getLong(ERA) - getLong(ERA); 1656 } 1657 throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); 1658 } 1659 return unit.between(this, end); 1660 } 1661 1662 long daysUntil(LocalDate end) { 1663 return end.toEpochDay() - toEpochDay(); // no overflow 1664 } 1665 1666 private long monthsUntil(LocalDate end) { 1667 long packed1 = getProlepticMonth() * 32L + getDayOfMonth(); // no overflow 1668 long packed2 = end.getProlepticMonth() * 32L + end.getDayOfMonth(); // no overflow 1669 return (packed2 - packed1) / 32; 1670 } 1671 1672 /** 1673 * Calculates the period between this date and another date as a {@code Period}. 1674 * <p> 1675 * This calculates the period between two dates in terms of years, months and days. 1676 * The start and end points are {@code this} and the specified date. 1677 * The result will be negative if the end is before the start. 1678 * The negative sign will be the same in each of year, month and day. 1679 * <p> 1680 * The calculation is performed using the ISO calendar system. 1681 * If necessary, the input date will be converted to ISO. 1682 * <p> 1683 * The start date is included, but the end date is not. 1684 * The period is calculated by removing complete months, then calculating 1685 * the remaining number of days, adjusting to ensure that both have the same sign. 1686 * The number of months is then normalized into years and months based on a 12 month year. 1687 * A month is considered to be complete if the end day-of-month is greater 1688 * than or equal to the start day-of-month. 1689 * For example, from {@code 2010-01-15} to {@code 2011-03-18} is "1 year, 2 months and 3 days". 1690 * <p> 1691 * There are two equivalent ways of using this method. 1692 * The first is to invoke this method. 1693 * The second is to use {@link Period#between(LocalDate, LocalDate)}: 1694 * <pre> 1695 * // these two lines are equivalent 1696 * period = start.until(end); 1697 * period = Period.between(start, end); 1698 * </pre> 1699 * The choice should be made based on which makes the code more readable. 1700 * 1701 * @param endDateExclusive the end date, exclusive, which may be in any chronology, not null 1702 * @return the period between this date and the end date, not null 1703 */ 1704 @Override 1705 public Period until(ChronoLocalDate endDateExclusive) { 1706 LocalDate end = LocalDate.from(endDateExclusive); 1707 long totalMonths = end.getProlepticMonth() - this.getProlepticMonth(); // safe 1708 int days = end.day - this.day; 1709 if (totalMonths > 0 && days < 0) { 1710 totalMonths--; 1711 LocalDate calcDate = this.plusMonths(totalMonths); 1712 days = (int) (end.toEpochDay() - calcDate.toEpochDay()); // safe 1713 } else if (totalMonths < 0 && days > 0) { 1714 totalMonths++; 1715 days -= end.lengthOfMonth(); 1716 } 1717 long years = totalMonths / 12; // safe 1718 int months = (int) (totalMonths % 12); // safe 1719 return Period.of(Math.toIntExact(years), months, days); 1720 } 1721 1722 /** 1723 * Returns a sequential ordered stream of dates. The returned stream starts from this date 1724 * (inclusive) and goes to {@code endExclusive} (exclusive) by an incremental step of 1 day. 1725 * <p> 1726 * This method is equivalent to {@code datesUntil(endExclusive, Period.ofDays(1))}. 1727 * 1728 * @param endExclusive the end date, exclusive, not null 1729 * @return a sequential {@code Stream} for the range of {@code LocalDate} values 1730 * @throws IllegalArgumentException if end date is before this date 1731 * @since 9 1732 */ 1733 public Stream<LocalDate> datesUntil(LocalDate endExclusive) { 1734 long end = endExclusive.toEpochDay(); 1735 long start = toEpochDay(); 1736 if (end < start) { 1737 throw new IllegalArgumentException(endExclusive + " < " + this); 1738 } 1739 return LongStream.range(start, end).mapToObj(LocalDate::ofEpochDay); 1740 } 1741 1742 /** 1743 * Returns a sequential ordered stream of dates by given incremental step. The returned stream 1744 * starts from this date (inclusive) and goes to {@code endExclusive} (exclusive). 1745 * <p> 1746 * The n-th date which appears in the stream is equal to {@code this.plus(step.multipliedBy(n))} 1747 * (but the result of step multiplication never overflows). For example, if this date is 1748 * {@code 2015-01-31}, the end date is {@code 2015-05-01} and the step is 1 month, then the 1749 * stream contains {@code 2015-01-31}, {@code 2015-02-28}, {@code 2015-03-31}, and 1750 * {@code 2015-04-30}. 1751 * 1752 * @param endExclusive the end date, exclusive, not null 1753 * @param step the non-zero, non-negative {@code Period} which represents the step. 1754 * @return a sequential {@code Stream} for the range of {@code LocalDate} values 1755 * @throws IllegalArgumentException if step is zero, or {@code step.getDays()} and 1756 * {@code step.toTotalMonths()} have opposite sign, or end date is before this date 1757 * and step is positive, or end date is after this date and step is negative 1758 * @since 9 1759 */ 1760 public Stream<LocalDate> datesUntil(LocalDate endExclusive, Period step) { 1761 if (step.isZero()) { 1762 throw new IllegalArgumentException("step is zero"); 1763 } 1764 long end = endExclusive.toEpochDay(); 1765 long start = toEpochDay(); 1766 long until = end - start; 1767 long months = step.toTotalMonths(); 1768 long days = step.getDays(); 1769 if ((months < 0 && days > 0) || (months > 0 && days < 0)) { 1770 throw new IllegalArgumentException("period months and days are of opposite sign"); 1771 } 1772 if (until == 0) { 1773 return Stream.empty(); 1774 } 1775 int sign = months > 0 || days > 0 ? 1 : -1; 1776 if (sign < 0 ^ until < 0) { 1777 throw new IllegalArgumentException(endExclusive + (sign < 0 ? " > " : " < ") + this); 1778 } 1779 if (months == 0) { 1780 long steps = (until - sign) / days; // non-negative 1781 return LongStream.rangeClosed(0, steps).mapToObj( 1782 n -> LocalDate.ofEpochDay(start + n * days)); 1783 } 1784 // 48699/1600 = 365.2425/12, no overflow, non-negative result 1785 long steps = until * 1600 / (months * 48699 + days * 1600) + 1; 1786 long addMonths = months * steps; 1787 long addDays = days * steps; 1788 long maxAddMonths = months > 0 ? MAX.getProlepticMonth() - getProlepticMonth() 1789 : getProlepticMonth() - MIN.getProlepticMonth(); 1790 // adjust steps estimation 1791 if (addMonths * sign > maxAddMonths 1792 || (plusMonths(addMonths).toEpochDay() + addDays) * sign >= end * sign) { 1793 steps--; 1794 addMonths -= months; 1795 addDays -= days; 1796 if (addMonths * sign > maxAddMonths 1797 || (plusMonths(addMonths).toEpochDay() + addDays) * sign >= end * sign) { 1798 steps--; 1799 } 1800 } 1801 return LongStream.rangeClosed(0, steps).mapToObj( 1802 n -> this.plusMonths(months * n).plusDays(days * n)); 1803 } 1804 1805 /** 1806 * Formats this date using the specified formatter. 1807 * <p> 1808 * This date will be passed to the formatter to produce a string. 1809 * 1810 * @param formatter the formatter to use, not null 1811 * @return the formatted date string, not null 1812 * @throws DateTimeException if an error occurs during printing 1813 */ 1814 @Override // override for Javadoc and performance 1815 public String format(DateTimeFormatter formatter) { 1816 Objects.requireNonNull(formatter, "formatter"); 1817 return formatter.format(this); 1818 } 1819 1820 //----------------------------------------------------------------------- 1821 /** 1822 * Combines this date with a time to create a {@code LocalDateTime}. 1823 * <p> 1824 * This returns a {@code LocalDateTime} formed from this date at the specified time. 1825 * All possible combinations of date and time are valid. 1826 * 1827 * @param time the time to combine with, not null 1828 * @return the local date-time formed from this date and the specified time, not null 1829 */ 1830 @Override 1831 public LocalDateTime atTime(LocalTime time) { 1832 return LocalDateTime.of(this, time); 1833 } 1834 1835 /** 1836 * Combines this date with a time to create a {@code LocalDateTime}. 1837 * <p> 1838 * This returns a {@code LocalDateTime} formed from this date at the 1839 * specified hour and minute. 1840 * The seconds and nanosecond fields will be set to zero. 1841 * The individual time fields must be within their valid range. 1842 * All possible combinations of date and time are valid. 1843 * 1844 * @param hour the hour-of-day to use, from 0 to 23 1845 * @param minute the minute-of-hour to use, from 0 to 59 1846 * @return the local date-time formed from this date and the specified time, not null 1847 * @throws DateTimeException if the value of any field is out of range 1848 */ 1849 public LocalDateTime atTime(int hour, int minute) { 1850 return atTime(LocalTime.of(hour, minute)); 1851 } 1852 1853 /** 1854 * Combines this date with a time to create a {@code LocalDateTime}. 1855 * <p> 1856 * This returns a {@code LocalDateTime} formed from this date at the 1857 * specified hour, minute and second. 1858 * The nanosecond field will be set to zero. 1859 * The individual time fields must be within their valid range. 1860 * All possible combinations of date and time are valid. 1861 * 1862 * @param hour the hour-of-day to use, from 0 to 23 1863 * @param minute the minute-of-hour to use, from 0 to 59 1864 * @param second the second-of-minute to represent, from 0 to 59 1865 * @return the local date-time formed from this date and the specified time, not null 1866 * @throws DateTimeException if the value of any field is out of range 1867 */ 1868 public LocalDateTime atTime(int hour, int minute, int second) { 1869 return atTime(LocalTime.of(hour, minute, second)); 1870 } 1871 1872 /** 1873 * Combines this date with a time to create a {@code LocalDateTime}. 1874 * <p> 1875 * This returns a {@code LocalDateTime} formed from this date at the 1876 * specified hour, minute, second and nanosecond. 1877 * The individual time fields must be within their valid range. 1878 * All possible combinations of date and time are valid. 1879 * 1880 * @param hour the hour-of-day to use, from 0 to 23 1881 * @param minute the minute-of-hour to use, from 0 to 59 1882 * @param second the second-of-minute to represent, from 0 to 59 1883 * @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999 1884 * @return the local date-time formed from this date and the specified time, not null 1885 * @throws DateTimeException if the value of any field is out of range 1886 */ 1887 public LocalDateTime atTime(int hour, int minute, int second, int nanoOfSecond) { 1888 return atTime(LocalTime.of(hour, minute, second, nanoOfSecond)); 1889 } 1890 1891 /** 1892 * Combines this date with an offset time to create an {@code OffsetDateTime}. 1893 * <p> 1894 * This returns an {@code OffsetDateTime} formed from this date at the specified time. 1895 * All possible combinations of date and time are valid. 1896 * 1897 * @param time the time to combine with, not null 1898 * @return the offset date-time formed from this date and the specified time, not null 1899 */ 1900 public OffsetDateTime atTime(OffsetTime time) { 1901 return OffsetDateTime.of(LocalDateTime.of(this, time.toLocalTime()), time.getOffset()); 1902 } 1903 1904 /** 1905 * Combines this date with the time of midnight to create a {@code LocalDateTime} 1906 * at the start of this date. 1907 * <p> 1908 * This returns a {@code LocalDateTime} formed from this date at the time of 1909 * midnight, 00:00, at the start of this date. 1910 * 1911 * @return the local date-time of midnight at the start of this date, not null 1912 */ 1913 public LocalDateTime atStartOfDay() { 1914 return LocalDateTime.of(this, LocalTime.MIDNIGHT); 1915 } 1916 1917 /** 1918 * Returns a zoned date-time from this date at the earliest valid time according 1919 * to the rules in the time-zone. 1920 * <p> 1921 * Time-zone rules, such as daylight savings, mean that not every local date-time 1922 * is valid for the specified zone, thus the local date-time may not be midnight. 1923 * <p> 1924 * In most cases, there is only one valid offset for a local date-time. 1925 * In the case of an overlap, there are two valid offsets, and the earlier one is used, 1926 * corresponding to the first occurrence of midnight on the date. 1927 * In the case of a gap, the zoned date-time will represent the instant just after the gap. 1928 * <p> 1929 * If the zone ID is a {@link ZoneOffset}, then the result always has a time of midnight. 1930 * <p> 1931 * To convert to a specific time in a given time-zone call {@link #atTime(LocalTime)} 1932 * followed by {@link LocalDateTime#atZone(ZoneId)}. 1933 * 1934 * @param zone the zone ID to use, not null 1935 * @return the zoned date-time formed from this date and the earliest valid time for the zone, not null 1936 */ 1937 public ZonedDateTime atStartOfDay(ZoneId zone) { 1938 Objects.requireNonNull(zone, "zone"); 1939 // need to handle case where there is a gap from 11:30 to 00:30 1940 // standard ZDT factory would result in 01:00 rather than 00:30 1941 LocalDateTime ldt = atTime(LocalTime.MIDNIGHT); 1942 if (zone instanceof ZoneOffset == false) { 1943 ZoneRules rules = zone.getRules(); 1944 ZoneOffsetTransition trans = rules.getTransition(ldt); 1945 if (trans != null && trans.isGap()) { 1946 ldt = trans.getDateTimeAfter(); 1947 } 1948 } 1949 return ZonedDateTime.of(ldt, zone); 1950 } 1951 1952 //----------------------------------------------------------------------- 1953 @Override 1954 public long toEpochDay() { 1955 long y = year; 1956 long m = month; 1957 long total = 0; 1958 total += 365 * y; 1959 if (y >= 0) { 1960 total += (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400; 1961 } else { 1962 total -= y / -4 - y / -100 + y / -400; 1963 } 1964 total += ((367 * m - 362) / 12); 1965 total += day - 1; 1966 if (m > 2) { 1967 total--; 1968 if (isLeapYear() == false) { 1969 total--; 1970 } 1971 } 1972 return total - DAYS_0000_TO_1970; 1973 } 1974 1975 /** 1976 * Converts this {@code LocalDate} to the number of seconds since the epoch 1977 * of 1970-01-01T00:00:00Z. 1978 * <p> 1979 * This combines this local date with the specified time and 1980 * offset to calculate the epoch-second value, which is the 1981 * number of elapsed seconds from 1970-01-01T00:00:00Z. 1982 * Instants on the time-line after the epoch are positive, earlier 1983 * are negative. 1984 * 1985 * @param time the local time, not null 1986 * @param offset the zone offset, not null 1987 * @return the number of seconds since the epoch of 1970-01-01T00:00:00Z, may be negative 1988 * @since 9 1989 */ 1990 public long toEpochSecond(LocalTime time, ZoneOffset offset) { 1991 Objects.requireNonNull(time, "time"); 1992 Objects.requireNonNull(offset, "offset"); 1993 long secs = toEpochDay() * SECONDS_PER_DAY + time.toSecondOfDay(); 1994 secs -= offset.getTotalSeconds(); 1995 return secs; 1996 } 1997 1998 //----------------------------------------------------------------------- 1999 /** 2000 * Compares this date to another date. 2001 * <p> 2002 * The comparison is primarily based on the date, from earliest to latest. 2003 * It is "consistent with equals", as defined by {@link Comparable}. 2004 * <p> 2005 * If all the dates being compared are instances of {@code LocalDate}, 2006 * then the comparison will be entirely based on the date. 2007 * If some dates being compared are in different chronologies, then the 2008 * chronology is also considered, see {@link java.time.chrono.ChronoLocalDate#compareTo}. 2009 * 2010 * @param other the other date to compare to, not null 2011 * @return the comparator value, negative if less, positive if greater 2012 */ 2013 @Override // override for Javadoc and performance 2014 public int compareTo(ChronoLocalDate other) { 2015 if (other instanceof LocalDate) { 2016 return compareTo0((LocalDate) other); 2017 } 2018 return ChronoLocalDate.super.compareTo(other); 2019 } 2020 2021 int compareTo0(LocalDate otherDate) { 2022 int cmp = (year - otherDate.year); 2023 if (cmp == 0) { 2024 cmp = (month - otherDate.month); 2025 if (cmp == 0) { 2026 cmp = (day - otherDate.day); 2027 } 2028 } 2029 return cmp; 2030 } 2031 2032 /** 2033 * Checks if this date is after the specified date. 2034 * <p> 2035 * This checks to see if this date represents a point on the 2036 * local time-line after the other date. 2037 * <pre> 2038 * LocalDate a = LocalDate.of(2012, 6, 30); 2039 * LocalDate b = LocalDate.of(2012, 7, 1); 2040 * a.isAfter(b) == false 2041 * a.isAfter(a) == false 2042 * b.isAfter(a) == true 2043 * </pre> 2044 * <p> 2045 * This method only considers the position of the two dates on the local time-line. 2046 * It does not take into account the chronology, or calendar system. 2047 * This is different from the comparison in {@link #compareTo(ChronoLocalDate)}, 2048 * but is the same approach as {@link ChronoLocalDate#timeLineOrder()}. 2049 * 2050 * @param other the other date to compare to, not null 2051 * @return true if this date is after the specified date 2052 */ 2053 @Override // override for Javadoc and performance 2054 public boolean isAfter(ChronoLocalDate other) { 2055 if (other instanceof LocalDate) { 2056 return compareTo0((LocalDate) other) > 0; 2057 } 2058 return ChronoLocalDate.super.isAfter(other); 2059 } 2060 2061 /** 2062 * Checks if this date is before the specified date. 2063 * <p> 2064 * This checks to see if this date represents a point on the 2065 * local time-line before the other date. 2066 * <pre> 2067 * LocalDate a = LocalDate.of(2012, 6, 30); 2068 * LocalDate b = LocalDate.of(2012, 7, 1); 2069 * a.isBefore(b) == true 2070 * a.isBefore(a) == false 2071 * b.isBefore(a) == false 2072 * </pre> 2073 * <p> 2074 * This method only considers the position of the two dates on the local time-line. 2075 * It does not take into account the chronology, or calendar system. 2076 * This is different from the comparison in {@link #compareTo(ChronoLocalDate)}, 2077 * but is the same approach as {@link ChronoLocalDate#timeLineOrder()}. 2078 * 2079 * @param other the other date to compare to, not null 2080 * @return true if this date is before the specified date 2081 */ 2082 @Override // override for Javadoc and performance 2083 public boolean isBefore(ChronoLocalDate other) { 2084 if (other instanceof LocalDate) { 2085 return compareTo0((LocalDate) other) < 0; 2086 } 2087 return ChronoLocalDate.super.isBefore(other); 2088 } 2089 2090 /** 2091 * Checks if this date is equal to the specified date. 2092 * <p> 2093 * This checks to see if this date represents the same point on the 2094 * local time-line as the other date. 2095 * <pre> 2096 * LocalDate a = LocalDate.of(2012, 6, 30); 2097 * LocalDate b = LocalDate.of(2012, 7, 1); 2098 * a.isEqual(b) == false 2099 * a.isEqual(a) == true 2100 * b.isEqual(a) == false 2101 * </pre> 2102 * <p> 2103 * This method only considers the position of the two dates on the local time-line. 2104 * It does not take into account the chronology, or calendar system. 2105 * This is different from the comparison in {@link #compareTo(ChronoLocalDate)} 2106 * but is the same approach as {@link ChronoLocalDate#timeLineOrder()}. 2107 * 2108 * @param other the other date to compare to, not null 2109 * @return true if this date is equal to the specified date 2110 */ 2111 @Override // override for Javadoc and performance 2112 public boolean isEqual(ChronoLocalDate other) { 2113 if (other instanceof LocalDate) { 2114 return compareTo0((LocalDate) other) == 0; 2115 } 2116 return ChronoLocalDate.super.isEqual(other); 2117 } 2118 2119 //----------------------------------------------------------------------- 2120 /** 2121 * Checks if this date is equal to another date. 2122 * <p> 2123 * Compares this {@code LocalDate} with another ensuring that the date is the same. 2124 * <p> 2125 * Only objects of type {@code LocalDate} are compared, other types return false. 2126 * To compare the dates of two {@code TemporalAccessor} instances, including dates 2127 * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator. 2128 * 2129 * @param obj the object to check, null returns false 2130 * @return true if this is equal to the other date 2131 */ 2132 @Override 2133 public boolean equals(Object obj) { 2134 if (this == obj) { 2135 return true; 2136 } 2137 if (obj instanceof LocalDate) { 2138 return compareTo0((LocalDate) obj) == 0; 2139 } 2140 return false; 2141 } 2142 2143 /** 2144 * A hash code for this date. 2145 * 2146 * @return a suitable hash code 2147 */ 2148 @Override 2149 public int hashCode() { 2150 int yearValue = year; 2151 int monthValue = month; 2152 int dayValue = day; 2153 return (yearValue & 0xFFFFF800) ^ ((yearValue << 11) + (monthValue << 6) + (dayValue)); 2154 } 2155 2156 //----------------------------------------------------------------------- 2157 /** 2158 * Outputs this date as a {@code String}, such as {@code 2007-12-03}. 2159 * <p> 2160 * The output will be in the ISO-8601 format {@code uuuu-MM-dd}. 2161 * 2162 * @return a string representation of this date, not null 2163 */ 2164 @Override 2165 public String toString() { 2166 int yearValue = year; 2167 int monthValue = month; 2168 int dayValue = day; 2169 int absYear = Math.abs(yearValue); 2170 StringBuilder buf = new StringBuilder(10); 2171 if (absYear < 1000) { 2172 if (yearValue < 0) { 2173 buf.append(yearValue - 10000).deleteCharAt(1); 2174 } else { 2175 buf.append(yearValue + 10000).deleteCharAt(0); 2176 } 2177 } else { 2178 if (yearValue > 9999) { 2179 buf.append('+'); 2180 } 2181 buf.append(yearValue); 2182 } 2183 return buf.append(monthValue < 10 ? "-0" : "-") 2184 .append(monthValue) 2185 .append(dayValue < 10 ? "-0" : "-") 2186 .append(dayValue) 2187 .toString(); 2188 } 2189 2190 //----------------------------------------------------------------------- 2191 /** 2192 * Writes the object using a 2193 * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>. 2194 * @serialData 2195 * <pre> 2196 * out.writeByte(3); // identifies a LocalDate 2197 * out.writeInt(year); 2198 * out.writeByte(month); 2199 * out.writeByte(day); 2200 * </pre> 2201 * 2202 * @return the instance of {@code Ser}, not null 2203 */ 2204 @java.io.Serial 2205 private Object writeReplace() { 2206 return new Ser(Ser.LOCAL_DATE_TYPE, this); 2207 } 2208 2209 /** 2210 * Defend against malicious streams. 2211 * 2212 * @param s the stream to read 2213 * @throws InvalidObjectException always 2214 */ 2215 @java.io.Serial 2216 private void readObject(ObjectInputStream s) throws InvalidObjectException { 2217 throw new InvalidObjectException("Deserialization via serialization delegate"); 2218 } 2219 2220 void writeExternal(DataOutput out) throws IOException { 2221 out.writeInt(year); 2222 out.writeByte(month); 2223 out.writeByte(day); 2224 } 2225 2226 static LocalDate readExternal(DataInput in) throws IOException { 2227 int year = in.readInt(); 2228 int month = in.readByte(); 2229 int dayOfMonth = in.readByte(); 2230 return LocalDate.of(year, month, dayOfMonth); 2231 } 2232 2233 }