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