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