Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/java/time/chrono/ChronoLocalDate.java
41159 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) 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.chrono;
63
64
import static java.time.temporal.ChronoField.EPOCH_DAY;
65
import static java.time.temporal.ChronoField.ERA;
66
import static java.time.temporal.ChronoField.YEAR;
67
import static java.time.temporal.ChronoUnit.DAYS;
68
69
import java.io.Serializable;
70
import java.time.DateTimeException;
71
import java.time.LocalDate;
72
import java.time.LocalTime;
73
import java.time.format.DateTimeFormatter;
74
import java.time.temporal.ChronoField;
75
import java.time.temporal.ChronoUnit;
76
import java.time.temporal.Temporal;
77
import java.time.temporal.TemporalAccessor;
78
import java.time.temporal.TemporalAdjuster;
79
import java.time.temporal.TemporalAmount;
80
import java.time.temporal.TemporalField;
81
import java.time.temporal.TemporalQueries;
82
import java.time.temporal.TemporalQuery;
83
import java.time.temporal.TemporalUnit;
84
import java.time.temporal.UnsupportedTemporalTypeException;
85
import java.util.Comparator;
86
import java.util.Objects;
87
88
/**
89
* A date without time-of-day or time-zone in an arbitrary chronology, intended
90
* for advanced globalization use cases.
91
* <p>
92
* <b>Most applications should declare method signatures, fields and variables
93
* as {@link LocalDate}, not this interface.</b>
94
* <p>
95
* A {@code ChronoLocalDate} is the abstract representation of a date where the
96
* {@code Chronology chronology}, or calendar system, is pluggable.
97
* The date is defined in terms of fields expressed by {@link TemporalField},
98
* where most common implementations are defined in {@link ChronoField}.
99
* The chronology defines how the calendar system operates and the meaning of
100
* the standard fields.
101
*
102
* <h2>When to use this interface</h2>
103
* The design of the API encourages the use of {@code LocalDate} rather than this
104
* interface, even in the case where the application needs to deal with multiple
105
* calendar systems.
106
* <p>
107
* This concept can seem surprising at first, as the natural way to globalize an
108
* application might initially appear to be to abstract the calendar system.
109
* However, as explored below, abstracting the calendar system is usually the wrong
110
* approach, resulting in logic errors and hard to find bugs.
111
* As such, it should be considered an application-wide architectural decision to choose
112
* to use this interface as opposed to {@code LocalDate}.
113
*
114
* <h3>Architectural issues to consider</h3>
115
* These are some of the points that must be considered before using this interface
116
* throughout an application.
117
* <p>
118
* 1) Applications using this interface, as opposed to using just {@code LocalDate},
119
* face a significantly higher probability of bugs. This is because the calendar system
120
* in use is not known at development time. A key cause of bugs is where the developer
121
* applies assumptions from their day-to-day knowledge of the ISO calendar system
122
* to code that is intended to deal with any arbitrary calendar system.
123
* The section below outlines how those assumptions can cause problems
124
* The primary mechanism for reducing this increased risk of bugs is a strong code review process.
125
* This should also be considered a extra cost in maintenance for the lifetime of the code.
126
* <p>
127
* 2) This interface does not enforce immutability of implementations.
128
* While the implementation notes indicate that all implementations must be immutable
129
* there is nothing in the code or type system to enforce this. Any method declared
130
* to accept a {@code ChronoLocalDate} could therefore be passed a poorly or
131
* maliciously written mutable implementation.
132
* <p>
133
* 3) Applications using this interface must consider the impact of eras.
134
* {@code LocalDate} shields users from the concept of eras, by ensuring that {@code getYear()}
135
* returns the proleptic year. That decision ensures that developers can think of
136
* {@code LocalDate} instances as consisting of three fields - year, month-of-year and day-of-month.
137
* By contrast, users of this interface must think of dates as consisting of four fields -
138
* era, year-of-era, month-of-year and day-of-month. The extra era field is frequently
139
* forgotten, yet it is of vital importance to dates in an arbitrary calendar system.
140
* For example, in the Japanese calendar system, the era represents the reign of an Emperor.
141
* Whenever one reign ends and another starts, the year-of-era is reset to one.
142
* <p>
143
* 4) The only agreed international standard for passing a date between two systems
144
* is the ISO-8601 standard which requires the ISO calendar system. Using this interface
145
* throughout the application will inevitably lead to the requirement to pass the date
146
* across a network or component boundary, requiring an application specific protocol or format.
147
* <p>
148
* 5) Long term persistence, such as a database, will almost always only accept dates in the
149
* ISO-8601 calendar system (or the related Julian-Gregorian). Passing around dates in other
150
* calendar systems increases the complications of interacting with persistence.
151
* <p>
152
* 6) Most of the time, passing a {@code ChronoLocalDate} throughout an application
153
* is unnecessary, as discussed in the last section below.
154
*
155
* <h3>False assumptions causing bugs in multi-calendar system code</h3>
156
* As indicated above, there are many issues to consider when try to use and manipulate a
157
* date in an arbitrary calendar system. These are some of the key issues.
158
* <p>
159
* Code that queries the day-of-month and assumes that the value will never be more than
160
* 31 is invalid. Some calendar systems have more than 31 days in some months.
161
* <p>
162
* Code that adds 12 months to a date and assumes that a year has been added is invalid.
163
* Some calendar systems have a different number of months, such as 13 in the Coptic or Ethiopic.
164
* <p>
165
* Code that adds one month to a date and assumes that the month-of-year value will increase
166
* by one or wrap to the next year is invalid. Some calendar systems have a variable number
167
* of months in a year, such as the Hebrew.
168
* <p>
169
* Code that adds one month, then adds a second one month and assumes that the day-of-month
170
* will remain close to its original value is invalid. Some calendar systems have a large difference
171
* between the length of the longest month and the length of the shortest month.
172
* For example, the Coptic or Ethiopic have 12 months of 30 days and 1 month of 5 days.
173
* <p>
174
* Code that adds seven days and assumes that a week has been added is invalid.
175
* Some calendar systems have weeks of other than seven days, such as the French Revolutionary.
176
* <p>
177
* Code that assumes that because the year of {@code date1} is greater than the year of {@code date2}
178
* then {@code date1} is after {@code date2} is invalid. This is invalid for all calendar systems
179
* when referring to the year-of-era, and especially untrue of the Japanese calendar system
180
* where the year-of-era restarts with the reign of every new Emperor.
181
* <p>
182
* Code that treats month-of-year one and day-of-month one as the start of the year is invalid.
183
* Not all calendar systems start the year when the month value is one.
184
* <p>
185
* In general, manipulating a date, and even querying a date, is wide open to bugs when the
186
* calendar system is unknown at development time. This is why it is essential that code using
187
* this interface is subjected to additional code reviews. It is also why an architectural
188
* decision to avoid this interface type is usually the correct one.
189
*
190
* <h3>Using LocalDate instead</h3>
191
* The primary alternative to using this interface throughout your application is as follows.
192
* <ul>
193
* <li>Declare all method signatures referring to dates in terms of {@code LocalDate}.
194
* <li>Either store the chronology (calendar system) in the user profile or lookup
195
* the chronology from the user locale
196
* <li>Convert the ISO {@code LocalDate} to and from the user's preferred calendar system during
197
* printing and parsing
198
* </ul>
199
* This approach treats the problem of globalized calendar systems as a localization issue
200
* and confines it to the UI layer. This approach is in keeping with other localization
201
* issues in the java platform.
202
* <p>
203
* As discussed above, performing calculations on a date where the rules of the calendar system
204
* are pluggable requires skill and is not recommended.
205
* Fortunately, the need to perform calculations on a date in an arbitrary calendar system
206
* is extremely rare. For example, it is highly unlikely that the business rules of a library
207
* book rental scheme will allow rentals to be for one month, where meaning of the month
208
* is dependent on the user's preferred calendar system.
209
* <p>
210
* A key use case for calculations on a date in an arbitrary calendar system is producing
211
* a month-by-month calendar for display and user interaction. Again, this is a UI issue,
212
* and use of this interface solely within a few methods of the UI layer may be justified.
213
* <p>
214
* In any other part of the system, where a date must be manipulated in a calendar system
215
* other than ISO, the use case will generally specify the calendar system to use.
216
* For example, an application may need to calculate the next Islamic or Hebrew holiday
217
* which may require manipulating the date.
218
* This kind of use case can be handled as follows:
219
* <ul>
220
* <li>start from the ISO {@code LocalDate} being passed to the method
221
* <li>convert the date to the alternate calendar system, which for this use case is known
222
* rather than arbitrary
223
* <li>perform the calculation
224
* <li>convert back to {@code LocalDate}
225
* </ul>
226
* Developers writing low-level frameworks or libraries should also avoid this interface.
227
* Instead, one of the two general purpose access interfaces should be used.
228
* Use {@link TemporalAccessor} if read-only access is required, or use {@link Temporal}
229
* if read-write access is required.
230
*
231
* @implSpec
232
* This interface must be implemented with care to ensure other classes operate correctly.
233
* All implementations that can be instantiated must be final, immutable and thread-safe.
234
* Subclasses should be Serializable wherever possible.
235
* <p>
236
* Additional calendar systems may be added to the system.
237
* See {@link Chronology} for more details.
238
*
239
* @since 1.8
240
*/
241
public interface ChronoLocalDate
242
extends Temporal, TemporalAdjuster, Comparable<ChronoLocalDate> {
243
244
/**
245
* Gets a comparator that compares {@code ChronoLocalDate} in
246
* time-line order ignoring the chronology.
247
* <p>
248
* This comparator differs from the comparison in {@link #compareTo} in that it
249
* only compares the underlying date and not the chronology.
250
* This allows dates in different calendar systems to be compared based
251
* on the position of the date on the local time-line.
252
* The underlying comparison is equivalent to comparing the epoch-day.
253
*
254
* @return a comparator that compares in time-line order ignoring the chronology
255
* @see #isAfter
256
* @see #isBefore
257
* @see #isEqual
258
*/
259
static Comparator<ChronoLocalDate> timeLineOrder() {
260
return (Comparator<ChronoLocalDate> & Serializable) (date1, date2) -> {
261
return Long.compare(date1.toEpochDay(), date2.toEpochDay());
262
};
263
}
264
265
//-----------------------------------------------------------------------
266
/**
267
* Obtains an instance of {@code ChronoLocalDate} from a temporal object.
268
* <p>
269
* This obtains a local date based on the specified temporal.
270
* A {@code TemporalAccessor} represents an arbitrary set of date and time information,
271
* which this factory converts to an instance of {@code ChronoLocalDate}.
272
* <p>
273
* The conversion extracts and combines the chronology and the date
274
* from the temporal object. The behavior is equivalent to using
275
* {@link Chronology#date(TemporalAccessor)} with the extracted chronology.
276
* Implementations are permitted to perform optimizations such as accessing
277
* those fields that are equivalent to the relevant objects.
278
* <p>
279
* This method matches the signature of the functional interface {@link TemporalQuery}
280
* allowing it to be used as a query via method reference, {@code ChronoLocalDate::from}.
281
*
282
* @param temporal the temporal object to convert, not null
283
* @return the date, not null
284
* @throws DateTimeException if unable to convert to a {@code ChronoLocalDate}
285
* @see Chronology#date(TemporalAccessor)
286
*/
287
static ChronoLocalDate from(TemporalAccessor temporal) {
288
if (temporal instanceof ChronoLocalDate) {
289
return (ChronoLocalDate) temporal;
290
}
291
Objects.requireNonNull(temporal, "temporal");
292
Chronology chrono = temporal.query(TemporalQueries.chronology());
293
if (chrono == null) {
294
throw new DateTimeException("Unable to obtain ChronoLocalDate from TemporalAccessor: " + temporal.getClass());
295
}
296
return chrono.date(temporal);
297
}
298
299
//-----------------------------------------------------------------------
300
/**
301
* Gets the chronology of this date.
302
* <p>
303
* The {@code Chronology} represents the calendar system in use.
304
* The era and other fields in {@link ChronoField} are defined by the chronology.
305
*
306
* @return the chronology, not null
307
*/
308
Chronology getChronology();
309
310
/**
311
* Gets the era, as defined by the chronology.
312
* <p>
313
* The era is, conceptually, the largest division of the time-line.
314
* Most calendar systems have a single epoch dividing the time-line into two eras.
315
* However, some have multiple eras, such as one for the reign of each leader.
316
* The exact meaning is determined by the {@code Chronology}.
317
* <p>
318
* All correctly implemented {@code Era} classes are singletons, thus it
319
* is valid code to write {@code date.getEra() == SomeChrono.ERA_NAME)}.
320
* <p>
321
* This default implementation uses {@link Chronology#eraOf(int)}.
322
*
323
* @return the chronology specific era constant applicable at this date, not null
324
*/
325
default Era getEra() {
326
return getChronology().eraOf(get(ERA));
327
}
328
329
/**
330
* Checks if the year is a leap year, as defined by the calendar system.
331
* <p>
332
* A leap-year is a year of a longer length than normal.
333
* The exact meaning is determined by the chronology with the constraint that
334
* a leap-year must imply a year-length longer than a non leap-year.
335
* <p>
336
* This default implementation uses {@link Chronology#isLeapYear(long)}.
337
*
338
* @return true if this date is in a leap year, false otherwise
339
*/
340
default boolean isLeapYear() {
341
return getChronology().isLeapYear(getLong(YEAR));
342
}
343
344
/**
345
* Returns the length of the month represented by this date, as defined by the calendar system.
346
* <p>
347
* This returns the length of the month in days.
348
*
349
* @return the length of the month in days
350
*/
351
int lengthOfMonth();
352
353
/**
354
* Returns the length of the year represented by this date, as defined by the calendar system.
355
* <p>
356
* This returns the length of the year in days.
357
* <p>
358
* The default implementation uses {@link #isLeapYear()} and returns 365 or 366.
359
*
360
* @return the length of the year in days
361
*/
362
default int lengthOfYear() {
363
return (isLeapYear() ? 366 : 365);
364
}
365
366
/**
367
* Checks if the specified field is supported.
368
* <p>
369
* This checks if the specified field can be queried on this date.
370
* If false, then calling the {@link #range(TemporalField) range},
371
* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
372
* methods will throw an exception.
373
* <p>
374
* The set of supported fields is defined by the chronology and normally includes
375
* all {@code ChronoField} date fields.
376
* <p>
377
* If the field is not a {@code ChronoField}, then the result of this method
378
* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
379
* passing {@code this} as the argument.
380
* Whether the field is supported is determined by the field.
381
*
382
* @param field the field to check, null returns false
383
* @return true if the field can be queried, false if not
384
*/
385
@Override
386
default boolean isSupported(TemporalField field) {
387
if (field instanceof ChronoField) {
388
return field.isDateBased();
389
}
390
return field != null && field.isSupportedBy(this);
391
}
392
393
/**
394
* Checks if the specified unit is supported.
395
* <p>
396
* This checks if the specified unit can be added to or subtracted from this date.
397
* If false, then calling the {@link #plus(long, TemporalUnit)} and
398
* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
399
* <p>
400
* The set of supported units is defined by the chronology and normally includes
401
* all {@code ChronoUnit} date units except {@code FOREVER}.
402
* <p>
403
* If the unit is not a {@code ChronoUnit}, then the result of this method
404
* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
405
* passing {@code this} as the argument.
406
* Whether the unit is supported is determined by the unit.
407
*
408
* @param unit the unit to check, null returns false
409
* @return true if the unit can be added/subtracted, false if not
410
*/
411
@Override
412
default boolean isSupported(TemporalUnit unit) {
413
if (unit instanceof ChronoUnit) {
414
return unit.isDateBased();
415
}
416
return unit != null && unit.isSupportedBy(this);
417
}
418
419
//-----------------------------------------------------------------------
420
// override for covariant return type
421
/**
422
* {@inheritDoc}
423
* @throws DateTimeException {@inheritDoc}
424
* @throws ArithmeticException {@inheritDoc}
425
*/
426
@Override
427
default ChronoLocalDate with(TemporalAdjuster adjuster) {
428
return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.with(adjuster));
429
}
430
431
/**
432
* {@inheritDoc}
433
* @throws DateTimeException {@inheritDoc}
434
* @throws UnsupportedTemporalTypeException {@inheritDoc}
435
* @throws ArithmeticException {@inheritDoc}
436
*/
437
@Override
438
default ChronoLocalDate with(TemporalField field, long newValue) {
439
if (field instanceof ChronoField) {
440
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
441
}
442
return ChronoLocalDateImpl.ensureValid(getChronology(), field.adjustInto(this, newValue));
443
}
444
445
/**
446
* {@inheritDoc}
447
* @throws DateTimeException {@inheritDoc}
448
* @throws ArithmeticException {@inheritDoc}
449
*/
450
@Override
451
default ChronoLocalDate plus(TemporalAmount amount) {
452
return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.plus(amount));
453
}
454
455
/**
456
* {@inheritDoc}
457
* @throws DateTimeException {@inheritDoc}
458
* @throws ArithmeticException {@inheritDoc}
459
*/
460
@Override
461
default ChronoLocalDate plus(long amountToAdd, TemporalUnit unit) {
462
if (unit instanceof ChronoUnit) {
463
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
464
}
465
return ChronoLocalDateImpl.ensureValid(getChronology(), unit.addTo(this, amountToAdd));
466
}
467
468
/**
469
* {@inheritDoc}
470
* @throws DateTimeException {@inheritDoc}
471
* @throws ArithmeticException {@inheritDoc}
472
*/
473
@Override
474
default ChronoLocalDate minus(TemporalAmount amount) {
475
return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.minus(amount));
476
}
477
478
/**
479
* {@inheritDoc}
480
* @throws DateTimeException {@inheritDoc}
481
* @throws UnsupportedTemporalTypeException {@inheritDoc}
482
* @throws ArithmeticException {@inheritDoc}
483
*/
484
@Override
485
default ChronoLocalDate minus(long amountToSubtract, TemporalUnit unit) {
486
return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.minus(amountToSubtract, unit));
487
}
488
489
//-----------------------------------------------------------------------
490
/**
491
* Queries this date using the specified query.
492
* <p>
493
* This queries this date using the specified query strategy object.
494
* The {@code TemporalQuery} object defines the logic to be used to
495
* obtain the result. Read the documentation of the query to understand
496
* what the result of this method will be.
497
* <p>
498
* The result of this method is obtained by invoking the
499
* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
500
* specified query passing {@code this} as the argument.
501
*
502
* @param <R> the type of the result
503
* @param query the query to invoke, not null
504
* @return the query result, null may be returned (defined by the query)
505
* @throws DateTimeException if unable to query (defined by the query)
506
* @throws ArithmeticException if numeric overflow occurs (defined by the query)
507
*/
508
@SuppressWarnings("unchecked")
509
@Override
510
default <R> R query(TemporalQuery<R> query) {
511
if (query == TemporalQueries.zoneId() || query == TemporalQueries.zone() || query == TemporalQueries.offset()) {
512
return null;
513
} else if (query == TemporalQueries.localTime()) {
514
return null;
515
} else if (query == TemporalQueries.chronology()) {
516
return (R) getChronology();
517
} else if (query == TemporalQueries.precision()) {
518
return (R) DAYS;
519
}
520
// inline TemporalAccessor.super.query(query) as an optimization
521
// non-JDK classes are not permitted to make this optimization
522
return query.queryFrom(this);
523
}
524
525
/**
526
* Adjusts the specified temporal object to have the same date as this object.
527
* <p>
528
* This returns a temporal object of the same observable type as the input
529
* with the date changed to be the same as this.
530
* <p>
531
* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
532
* passing {@link ChronoField#EPOCH_DAY} as the field.
533
* <p>
534
* In most cases, it is clearer to reverse the calling pattern by using
535
* {@link Temporal#with(TemporalAdjuster)}:
536
* <pre>
537
* // these two lines are equivalent, but the second approach is recommended
538
* temporal = thisLocalDate.adjustInto(temporal);
539
* temporal = temporal.with(thisLocalDate);
540
* </pre>
541
* <p>
542
* This instance is immutable and unaffected by this method call.
543
*
544
* @param temporal the target object to be adjusted, not null
545
* @return the adjusted object, not null
546
* @throws DateTimeException if unable to make the adjustment
547
* @throws ArithmeticException if numeric overflow occurs
548
*/
549
@Override
550
default Temporal adjustInto(Temporal temporal) {
551
return temporal.with(EPOCH_DAY, toEpochDay());
552
}
553
554
/**
555
* Calculates the amount of time until another date in terms of the specified unit.
556
* <p>
557
* This calculates the amount of time between two {@code ChronoLocalDate}
558
* objects in terms of a single {@code TemporalUnit}.
559
* The start and end points are {@code this} and the specified date.
560
* The result will be negative if the end is before the start.
561
* The {@code Temporal} passed to this method is converted to a
562
* {@code ChronoLocalDate} using {@link Chronology#date(TemporalAccessor)}.
563
* The calculation returns a whole number, representing the number of
564
* complete units between the two dates.
565
* For example, the amount in days between two dates can be calculated
566
* using {@code startDate.until(endDate, DAYS)}.
567
* <p>
568
* There are two equivalent ways of using this method.
569
* The first is to invoke this method.
570
* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
571
* <pre>
572
* // these two lines are equivalent
573
* amount = start.until(end, MONTHS);
574
* amount = MONTHS.between(start, end);
575
* </pre>
576
* The choice should be made based on which makes the code more readable.
577
* <p>
578
* The calculation is implemented in this method for {@link ChronoUnit}.
579
* The units {@code DAYS}, {@code WEEKS}, {@code MONTHS}, {@code YEARS},
580
* {@code DECADES}, {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS}
581
* should be supported by all implementations.
582
* Other {@code ChronoUnit} values will throw an exception.
583
* <p>
584
* If the unit is not a {@code ChronoUnit}, then the result of this method
585
* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
586
* passing {@code this} as the first argument and the converted input temporal as
587
* the second argument.
588
* <p>
589
* This instance is immutable and unaffected by this method call.
590
*
591
* @param endExclusive the end date, exclusive, which is converted to a
592
* {@code ChronoLocalDate} in the same chronology, not null
593
* @param unit the unit to measure the amount in, not null
594
* @return the amount of time between this date and the end date
595
* @throws DateTimeException if the amount cannot be calculated, or the end
596
* temporal cannot be converted to a {@code ChronoLocalDate}
597
* @throws UnsupportedTemporalTypeException if the unit is not supported
598
* @throws ArithmeticException if numeric overflow occurs
599
*/
600
@Override // override for Javadoc
601
long until(Temporal endExclusive, TemporalUnit unit);
602
603
/**
604
* Calculates the period between this date and another date as a {@code ChronoPeriod}.
605
* <p>
606
* This calculates the period between two dates. All supplied chronologies
607
* calculate the period using years, months and days, however the
608
* {@code ChronoPeriod} API allows the period to be represented using other units.
609
* <p>
610
* The start and end points are {@code this} and the specified date.
611
* The result will be negative if the end is before the start.
612
* The negative sign will be the same in each of year, month and day.
613
* <p>
614
* The calculation is performed using the chronology of this date.
615
* If necessary, the input date will be converted to match.
616
* <p>
617
* This instance is immutable and unaffected by this method call.
618
*
619
* @param endDateExclusive the end date, exclusive, which may be in any chronology, not null
620
* @return the period between this date and the end date, not null
621
* @throws DateTimeException if the period cannot be calculated
622
* @throws ArithmeticException if numeric overflow occurs
623
*/
624
ChronoPeriod until(ChronoLocalDate endDateExclusive);
625
626
/**
627
* Formats this date using the specified formatter.
628
* <p>
629
* This date will be passed to the formatter to produce a string.
630
* <p>
631
* The default implementation must behave as follows:
632
* <pre>
633
* return formatter.format(this);
634
* </pre>
635
*
636
* @param formatter the formatter to use, not null
637
* @return the formatted date string, not null
638
* @throws DateTimeException if an error occurs during printing
639
*/
640
default String format(DateTimeFormatter formatter) {
641
Objects.requireNonNull(formatter, "formatter");
642
return formatter.format(this);
643
}
644
645
//-----------------------------------------------------------------------
646
/**
647
* Combines this date with a time to create a {@code ChronoLocalDateTime}.
648
* <p>
649
* This returns a {@code ChronoLocalDateTime} formed from this date at the specified time.
650
* All possible combinations of date and time are valid.
651
*
652
* @param localTime the local time to use, not null
653
* @return the local date-time formed from this date and the specified time, not null
654
*/
655
@SuppressWarnings("unchecked")
656
default ChronoLocalDateTime<?> atTime(LocalTime localTime) {
657
return ChronoLocalDateTimeImpl.of(this, localTime);
658
}
659
660
//-----------------------------------------------------------------------
661
/**
662
* Converts this date to the Epoch Day.
663
* <p>
664
* The {@link ChronoField#EPOCH_DAY Epoch Day count} is a simple
665
* incrementing count of days where day 0 is 1970-01-01 (ISO).
666
* This definition is the same for all chronologies, enabling conversion.
667
* <p>
668
* This default implementation queries the {@code EPOCH_DAY} field.
669
*
670
* @return the Epoch Day equivalent to this date
671
*/
672
default long toEpochDay() {
673
return getLong(EPOCH_DAY);
674
}
675
676
//-----------------------------------------------------------------------
677
/**
678
* Compares this date to another date, including the chronology.
679
* <p>
680
* The comparison is based first on the underlying time-line date, then
681
* on the chronology.
682
* It is "consistent with equals", as defined by {@link Comparable}.
683
* <p>
684
* For example, the following is the comparator order:
685
* <ol>
686
* <li>{@code 2012-12-03 (ISO)}</li>
687
* <li>{@code 2012-12-04 (ISO)}</li>
688
* <li>{@code 2555-12-04 (ThaiBuddhist)}</li>
689
* <li>{@code 2012-12-05 (ISO)}</li>
690
* </ol>
691
* Values #2 and #3 represent the same date on the time-line.
692
* When two values represent the same date, the chronology ID is compared to distinguish them.
693
* This step is needed to make the ordering "consistent with equals".
694
* <p>
695
* If all the date objects being compared are in the same chronology, then the
696
* additional chronology stage is not required and only the local date is used.
697
* To compare the dates of two {@code TemporalAccessor} instances, including dates
698
* in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.
699
* <p>
700
* This default implementation performs the comparison defined above.
701
*
702
* @param other the other date to compare to, not null
703
* @return the comparator value, negative if less, positive if greater
704
*/
705
@Override
706
default int compareTo(ChronoLocalDate other) {
707
int cmp = Long.compare(toEpochDay(), other.toEpochDay());
708
if (cmp == 0) {
709
cmp = getChronology().compareTo(other.getChronology());
710
}
711
return cmp;
712
}
713
714
/**
715
* Checks if this date is after the specified date ignoring the chronology.
716
* <p>
717
* This method differs from the comparison in {@link #compareTo} in that it
718
* only compares the underlying date and not the chronology.
719
* This allows dates in different calendar systems to be compared based
720
* on the time-line position.
721
* This is equivalent to using {@code date1.toEpochDay() > date2.toEpochDay()}.
722
* <p>
723
* This default implementation performs the comparison based on the epoch-day.
724
*
725
* @param other the other date to compare to, not null
726
* @return true if this is after the specified date
727
*/
728
default boolean isAfter(ChronoLocalDate other) {
729
return this.toEpochDay() > other.toEpochDay();
730
}
731
732
/**
733
* Checks if this date is before the specified date ignoring the chronology.
734
* <p>
735
* This method differs from the comparison in {@link #compareTo} in that it
736
* only compares the underlying date and not the chronology.
737
* This allows dates in different calendar systems to be compared based
738
* on the time-line position.
739
* This is equivalent to using {@code date1.toEpochDay() < date2.toEpochDay()}.
740
* <p>
741
* This default implementation performs the comparison based on the epoch-day.
742
*
743
* @param other the other date to compare to, not null
744
* @return true if this is before the specified date
745
*/
746
default boolean isBefore(ChronoLocalDate other) {
747
return this.toEpochDay() < other.toEpochDay();
748
}
749
750
/**
751
* Checks if this date is equal to the specified date ignoring the chronology.
752
* <p>
753
* This method differs from the comparison in {@link #compareTo} in that it
754
* only compares the underlying date and not the chronology.
755
* This allows dates in different calendar systems to be compared based
756
* on the time-line position.
757
* This is equivalent to using {@code date1.toEpochDay() == date2.toEpochDay()}.
758
* <p>
759
* This default implementation performs the comparison based on the epoch-day.
760
*
761
* @param other the other date to compare to, not null
762
* @return true if the underlying date is equal to the specified date
763
*/
764
default boolean isEqual(ChronoLocalDate other) {
765
return this.toEpochDay() == other.toEpochDay();
766
}
767
768
//-----------------------------------------------------------------------
769
/**
770
* Checks if this date is equal to another date, including the chronology.
771
* <p>
772
* Compares this date with another ensuring that the date and chronology are the same.
773
* <p>
774
* To compare the dates of two {@code TemporalAccessor} instances, including dates
775
* in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.
776
*
777
* @param obj the object to check, null returns false
778
* @return true if this is equal to the other date
779
*/
780
@Override
781
boolean equals(Object obj);
782
783
/**
784
* A hash code for this date.
785
*
786
* @return a suitable hash code
787
*/
788
@Override
789
int hashCode();
790
791
//-----------------------------------------------------------------------
792
/**
793
* Outputs this date as a {@code String}.
794
* <p>
795
* The output will include the full local date.
796
*
797
* @return the formatted date, not null
798
*/
799
@Override
800
String toString();
801
802
}
803
804