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