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