-
Notifications
You must be signed in to change notification settings - Fork 668
/
ChronoLocalDateImpl.java
578 lines (515 loc) · 25.8 KB
/
ChronoLocalDateImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time.chrono;
import java.io.Serializable;
import java.time.DateTimeException;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.time.temporal.ValueRange;
import java.util.Objects;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.ERA;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;
import static java.time.temporal.ChronoField.YEAR_OF_ERA;
/**
* A date expressed in terms of a standard year-month-day calendar system.
* <p>
* This class is used by applications seeking to handle dates in non-ISO calendar systems.
* For example, the Japanese, Minguo, Thai Buddhist and others.
* <p>
* {@code ChronoLocalDate} is built on the generic concepts of year, month and day.
* The calendar system, represented by a {@link java.time.chrono.Chronology}, expresses the relationship between
* the fields and this class allows the resulting date to be manipulated.
* <p>
* Note that not all calendar systems are suitable for use with this class.
* For example, the Mayan calendar uses a system that bears no relation to years, months and days.
* <p>
* The API design encourages the use of {@code LocalDate} for the majority of the application.
* This includes code to read and write from a persistent data store, such as a database,
* and to send dates and times across a network. The {@code ChronoLocalDate} instance is then used
* at the user interface level to deal with localized input/output.
*
* <P>Example: </p>
* <pre>
* System.out.printf("Example()%n");
* // Enumerate the list of available calendars and print today for each
* Set<Chronology> chronos = Chronology.getAvailableChronologies();
* for (Chronology chrono : chronos) {
* ChronoLocalDate date = chrono.dateNow();
* System.out.printf(" %20s: %s%n", chrono.getID(), date.toString());
* }
*
* // Print the Hijrah date and calendar
* ChronoLocalDate date = Chronology.of("Hijrah").dateNow();
* int day = date.get(ChronoField.DAY_OF_MONTH);
* int dow = date.get(ChronoField.DAY_OF_WEEK);
* int month = date.get(ChronoField.MONTH_OF_YEAR);
* int year = date.get(ChronoField.YEAR);
* System.out.printf(" Today is %s %s %d-%s-%d%n", date.getChronology().getID(),
* dow, day, month, year);
*
* // Print today's date and the last day of the year
* ChronoLocalDate now1 = Chronology.of("Hijrah").dateNow();
* ChronoLocalDate first = now1.with(ChronoField.DAY_OF_MONTH, 1)
* .with(ChronoField.MONTH_OF_YEAR, 1);
* ChronoLocalDate last = first.plus(1, ChronoUnit.YEARS)
* .minus(1, ChronoUnit.DAYS);
* System.out.printf(" Today is %s: start: %s; end: %s%n", last.getChronology().getID(),
* first, last);
* </pre>
*
* <h3>Adding Calendars</h3>
* <p> The set of calendars is extensible by defining a subclass of {@link ChronoLocalDate}
* to represent a date instance and an implementation of {@code Chronology}
* to be the factory for the ChronoLocalDate subclass.
* </p>
* <p> To permit the discovery of the additional calendar types the implementation of
* {@code Chronology} must be registered as a Service implementing the {@code Chronology} interface
* in the {@code META-INF/Services} file as per the specification of {@link java.util.ServiceLoader}.
* The subclass must function according to the {@code Chronology} class description and must provide its
* {@link java.time.chrono.Chronology#getId() chronlogy ID} and {@link Chronology#getCalendarType() calendar type}. </p>
*
* @param <D> the ChronoLocalDate of this date-time
*
* @implSpec This abstract class must be implemented with care to ensure other classes operate correctly.
* All implementations that can be instantiated must be final, immutable and thread-safe.
* Subclasses should be Serializable wherever possible.
* @since 1.8
*/
// "本地日期"的抽象实现,"日期"基于[非ISO]历法系统
abstract class ChronoLocalDateImpl<D extends ChronoLocalDate> implements ChronoLocalDate, Temporal, TemporalAdjuster, Serializable {
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates an instance.
*/
ChronoLocalDateImpl() {
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 增加 ████████████████████████████████████████████████████████████████████████████████┓ */
/*
* 对当前时间量的值与参数中的"时间段"求和
*
* 如果求和后的值与当前时间量的值相等,则直接返回当前时间量对象。
* 否则,需要构造"求和"后的新对象再返回。
*/
@Override
@SuppressWarnings("unchecked")
public D plus(TemporalAmount amount) {
return (D) ChronoLocalDate.super.plus(amount);
}
/*
* 对当前时间量的值累加amountToAdd个unit单位的时间量
*
* 如果累加后的值与当前时间量的值相等,则直接返回当前时间量对象。
* 否则,需要构造"累加"操作后的新对象再返回。
*/
@Override
@SuppressWarnings("unchecked")
public D plus(long amountToAdd, TemporalUnit unit) {
if(unit instanceof ChronoUnit) {
ChronoUnit f = (ChronoUnit) unit;
switch(f) {
case DAYS:
return plusDays(amountToAdd);
case WEEKS:
return plusDays(Math.multiplyExact(amountToAdd, 7));
case MONTHS:
return plusMonths(amountToAdd);
case YEARS:
return plusYears(amountToAdd);
case DECADES:
return plusYears(Math.multiplyExact(amountToAdd, 10));
case CENTURIES:
return plusYears(Math.multiplyExact(amountToAdd, 100));
case MILLENNIA:
return plusYears(Math.multiplyExact(amountToAdd, 1000));
case ERAS:
return with(ERA, Math.addExact(getLong(ERA), amountToAdd));
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return (D) ChronoLocalDate.super.plus(amountToAdd, unit);
}
/**
* Returns a copy of this date with the specified number of years added.
* <p>
* This adds the specified period in years to the date.
* In some cases, adding years can cause the resulting date to become invalid.
* If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure
* that the result is valid. Typically this will select the last valid day of the month.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToAdd the years to add, may be negative
*
* @return a date based on this one with the years added, not null
*
* @throws DateTimeException if the result exceeds the supported date range
*/
// 在当前时间量的值上累加yearsToAdd年
abstract D plusYears(long yearsToAdd);
/**
* Returns a copy of this date with the specified number of months added.
* <p>
* This adds the specified period in months to the date.
* In some cases, adding months can cause the resulting date to become invalid.
* If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure
* that the result is valid. Typically this will select the last valid day of the month.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param monthsToAdd the months to add, may be negative
*
* @return a date based on this one with the months added, not null
*
* @throws DateTimeException if the result exceeds the supported date range
*/
// 在当前时间量的值上累加monthsToAdd月
abstract D plusMonths(long monthsToAdd);
/**
* Returns a copy of this date with the specified number of weeks added.
* <p>
* This adds the specified period in weeks to the date.
* In some cases, adding weeks can cause the resulting date to become invalid.
* If this occurs, then other fields will be adjusted to ensure that the result is valid.
* <p>
* The default implementation uses {@link #plusDays(long)} using a 7 day week.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param weeksToAdd the weeks to add, may be negative
*
* @return a date based on this one with the weeks added, not null
*
* @throws DateTimeException if the result exceeds the supported date range
*/
// 在当前时间量的值上累加weeksToAdd周
D plusWeeks(long weeksToAdd) {
return plusDays(Math.multiplyExact(weeksToAdd, 7));
}
/**
* Returns a copy of this date with the specified number of days added.
* <p>
* This adds the specified period in days to the date.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param daysToAdd the days to add, may be negative
*
* @return a date based on this one with the days added, not null
*
* @throws DateTimeException if the result exceeds the supported date range
*/
// 在当前时间量的值上累加daysToAdd天
abstract D plusDays(long daysToAdd);
/*▲ 增加 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 减少 ████████████████████████████████████████████████████████████████████████████████┓ */
/*
* 对当前时间量的值与参数中的"时间段"求差
*
* 如果求差后的值与当前时间量的值相等,则直接返回当前时间量对象。
* 否则,需要构造"求差"后的新对象再返回。
*/
@Override
@SuppressWarnings("unchecked")
public D minus(TemporalAmount amount) {
return (D) ChronoLocalDate.super.minus(amount);
}
/*
* 对当前时间量的值减去amountToSubtract个unit单位的时间量
*
* 如果减去后的值与当前时间量的值相等,则直接返回当前时间量对象。
* 否则,需要构造"减去"操作后的新对象再返回。
*/
@Override
@SuppressWarnings("unchecked")
public D minus(long amountToSubtract, TemporalUnit unit) {
return (D) ChronoLocalDate.super.minus(amountToSubtract, unit);
}
/**
* Returns a copy of this date with the specified number of years subtracted.
* <p>
* This subtracts the specified period in years to the date.
* In some cases, subtracting years can cause the resulting date to become invalid.
* If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure
* that the result is valid. Typically this will select the last valid day of the month.
* <p>
* The default implementation uses {@link #plusYears(long)}.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToSubtract the years to subtract, may be negative
*
* @return a date based on this one with the years subtracted, not null
*
* @throws DateTimeException if the result exceeds the supported date range
*/
// 在当前时间量的值上减去yearsToSubtract年
@SuppressWarnings("unchecked")
D minusYears(long yearsToSubtract) {
if(yearsToSubtract == Long.MIN_VALUE) {
return ((ChronoLocalDateImpl<D>) plusYears(Long.MAX_VALUE)).plusYears(1);
}
return plusYears(-yearsToSubtract);
}
/**
* Returns a copy of this date with the specified number of months subtracted.
* <p>
* This subtracts the specified period in months to the date.
* In some cases, subtracting months can cause the resulting date to become invalid.
* If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure
* that the result is valid. Typically this will select the last valid day of the month.
* <p>
* The default implementation uses {@link #plusMonths(long)}.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param monthsToSubtract the months to subtract, may be negative
*
* @return a date based on this one with the months subtracted, not null
*
* @throws DateTimeException if the result exceeds the supported date range
*/
// 在当前时间量的值上减去monthsToSubtract月
@SuppressWarnings("unchecked")
D minusMonths(long monthsToSubtract) {
if(monthsToSubtract == Long.MIN_VALUE) {
return ((ChronoLocalDateImpl<D>) plusMonths(Long.MAX_VALUE)).plusMonths(1);
}
return plusMonths(-monthsToSubtract);
}
/**
* Returns a copy of this date with the specified number of weeks subtracted.
* <p>
* This subtracts the specified period in weeks to the date.
* In some cases, subtracting weeks can cause the resulting date to become invalid.
* If this occurs, then other fields will be adjusted to ensure that the result is valid.
* <p>
* The default implementation uses {@link #plusWeeks(long)}.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param weeksToSubtract the weeks to subtract, may be negative
*
* @return a date based on this one with the weeks subtracted, not null
*
* @throws DateTimeException if the result exceeds the supported date range
*/
// 在当前时间量的值上减去weeksToSubtract周
@SuppressWarnings("unchecked")
D minusWeeks(long weeksToSubtract) {
if(weeksToSubtract == Long.MIN_VALUE) {
return ((ChronoLocalDateImpl<D>) plusWeeks(Long.MAX_VALUE)).plusWeeks(1);
}
return plusWeeks(-weeksToSubtract);
}
/**
* Returns a copy of this date with the specified number of days subtracted.
* <p>
* This subtracts the specified period in days to the date.
* <p>
* The default implementation uses {@link #plusDays(long)}.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param daysToSubtract the days to subtract, may be negative
*
* @return a date based on this one with the days subtracted, not null
*
* @throws DateTimeException if the result exceeds the supported date range
*/
// 在当前时间量的值上减去daysToSubtract天
@SuppressWarnings("unchecked")
D minusDays(long daysToSubtract) {
if(daysToSubtract == Long.MIN_VALUE) {
return ((ChronoLocalDateImpl<D>) plusDays(Long.MAX_VALUE)).plusDays(1);
}
return plusDays(-daysToSubtract);
}
/*▲ 减少 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 整合 ████████████████████████████████████████████████████████████████████████████████┓ */
/*
* 使用指定的时间量整合器adjuster来构造时间量对象。
*
* 如果整合后的值与当前时间量中的值相等,则直接返回当前时间量对象。
* 否则,需要构造"整合"后的新对象再返回。
*/
@Override
@SuppressWarnings("unchecked")
public D with(TemporalAdjuster adjuster) {
return (D) ChronoLocalDate.super.with(adjuster);
}
/*
* 通过整合指定类型的字段和当前时间量中的其他类型的字段来构造时间量对象。
*
* 如果整合后的值与当前时间量中的值相等,则直接返回当前时间量对象。
* 否则,需要构造"整合"后的新对象再返回。
*
* field : 待整合的字段(类型)
* newValue: field的原始值,需要根据filed的类型进行放缩
*
* 默认是不支持ChronoField类型的字段的,但是子类的实现中可以支持它
*/
@Override
@SuppressWarnings("unchecked")
public D with(TemporalField field, long value) {
return (D) ChronoLocalDate.super.with(field, value);
}
/*▲ 整合 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 杂项 ████████████████████████████████████████████████████████████████████████████████┓ */
// 计算当前时间量到目标时间量endExclusive之间相差多少个unit单位的时间值
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
Objects.requireNonNull(endExclusive, "endExclusive");
Objects.requireNonNull(unit, "unit");
ChronoLocalDate end = getChronology().date(endExclusive);
if(unit instanceof ChronoUnit) {
switch((ChronoUnit) unit) {
case DAYS:
return daysUntil(end);
case WEEKS:
return daysUntil(end) / 7;
case MONTHS:
return monthsUntil(end);
case YEARS:
return monthsUntil(end) / 12;
case DECADES:
return monthsUntil(end) / 120;
case CENTURIES:
return monthsUntil(end) / 1200;
case MILLENNIA:
return monthsUntil(end) / 12000;
case ERAS:
return end.getLong(ERA) - getLong(ERA);
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.between(this, end);
}
/*▲ 杂项 ████████████████████████████████████████████████████████████████████████████████┛ */
// 计算当前日期到参数中日期相差的天数
private long daysUntil(ChronoLocalDate end) {
return end.toEpochDay() - toEpochDay(); // no overflow
}
// 计算当前日期到参数中日期相差的月数
private long monthsUntil(ChronoLocalDate end) {
// 返回时间量字段MONTH_OF_YEAR的取值区间
ValueRange range = getChronology().range(MONTH_OF_YEAR);
if(range.getMaximum() != 12) {
throw new IllegalStateException("ChronoLocalDateImpl only supports Chronologies with 12 months per year");
}
long packed1 = getLong(PROLEPTIC_MONTH) * 32L + get(DAY_OF_MONTH); // no overflow
long packed2 = end.getLong(PROLEPTIC_MONTH) * 32L + end.get(DAY_OF_MONTH); // no overflow
return (packed2 - packed1) / 32;
}
/**
* Casts the {@code Temporal} to {@code ChronoLocalDate} ensuring it bas the specified chronology.
*
* @param chrono the chronology to check for, not null
* @param temporal a date-time to cast, not null
*
* @return the date-time checked and cast to {@code ChronoLocalDate}, not null
*
* @throws ClassCastException if the date-time cannot be cast to ChronoLocalDate
* or the chronology is not equal this Chronology
*/
// 判断指定的历法系统chrono是否与时间量temporal的历法系统相同
static <D extends ChronoLocalDate> D ensureValid(Chronology chrono, Temporal temporal) {
@SuppressWarnings("unchecked")
D other = (D) temporal;
if(!chrono.equals(other.getChronology())) {
throw new ClassCastException("Chronology mismatch, expected: " + chrono.getId() + ", actual: " + other.getChronology().getId());
}
return other;
}
@Override
public String toString() {
// getLong() reduces chances of exceptions in toString()
long yoe = getLong(YEAR_OF_ERA);
long moy = getLong(MONTH_OF_YEAR);
long dom = getLong(DAY_OF_MONTH);
StringBuilder buf = new StringBuilder(30);
buf.append(getChronology().toString()).append(" ").append(getEra()).append(" ").append(yoe).append(moy<10 ? "-0" : "-").append(moy).append(dom<10 ? "-0" : "-").append(dom);
return buf.toString();
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj instanceof ChronoLocalDate) {
return compareTo((ChronoLocalDate) obj) == 0;
}
return false;
}
@Override
public int hashCode() {
long epDay = toEpochDay();
return getChronology().hashCode() ^ ((int) (epDay ^ (epDay >>> 32)));
}
/*▼ 序列化 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Serialization version.
*/
private static final long serialVersionUID = 6282433883239719096L;
/*▲ 序列化 ████████████████████████████████████████████████████████████████████████████████┛ */
}