-
Notifications
You must be signed in to change notification settings - Fork 668
/
Duration.java
2042 lines (1842 loc) · 83.4 KB
/
Duration.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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012, 2018, 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.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2007-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;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.time.LocalTime.MINUTES_PER_HOUR;
import static java.time.LocalTime.NANOS_PER_MILLI;
import static java.time.LocalTime.NANOS_PER_SECOND;
import static java.time.LocalTime.SECONDS_PER_DAY;
import static java.time.LocalTime.SECONDS_PER_HOUR;
import static java.time.LocalTime.SECONDS_PER_MINUTE;
import static java.time.temporal.ChronoField.NANO_OF_SECOND;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.NANOS;
import static java.time.temporal.ChronoUnit.SECONDS;
/**
* A time-based amount of time, such as '34.5 seconds'.
* <p>
* This class models a quantity or amount of time in terms of seconds and nanoseconds.
* It can be accessed using other duration-based units, such as minutes and hours.
* In addition, the {@link ChronoUnit#DAYS DAYS} unit can be used and is treated as
* exactly equal to 24 hours, thus ignoring daylight savings effects.
* See {@link Period} for the date-based equivalent to this class.
* <p>
* A physical duration could be of infinite length.
* For practicality, the duration is stored with constraints similar to {@link Instant}.
* The duration uses nanosecond resolution with a maximum value of the seconds that can
* be held in a {@code long}. This is greater than the current estimated age of the universe.
* <p>
* The range of a duration requires the storage of a number larger than a {@code long}.
* To achieve this, the class stores a {@code long} representing seconds and an {@code int}
* representing nanosecond-of-second, which will always be between 0 and 999,999,999.
* The model is of a directed duration, meaning that the duration may be negative.
* <p>
* The duration is measured in "seconds", but these are not necessarily identical to
* the scientific "SI second" definition based on atomic clocks.
* This difference only impacts durations measured near a leap-second and should not affect
* most applications.
* See {@link Instant} for a discussion as to the meaning of the second and time-scales.
*
* <p>
* This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
* class; use of identity-sensitive operations (including reference equality
* ({@code ==}), identity hash code, or synchronization) on instances of
* {@code Duration} may have unpredictable results and should be avoided.
* The {@code equals} method should be used for comparisons.
*
* @implSpec This class is immutable and thread-safe.
* @since 1.8
*/
// 时间段,包含秒/纳秒部件,精确到纳秒
public final class Duration implements TemporalAmount, Comparable<Duration>, Serializable {
/**
* Constant for nanos per second.
*/
private static final BigInteger BI_NANOS_PER_SECOND = BigInteger.valueOf(NANOS_PER_SECOND);
/**
* Constant for a duration of zero.
*/
public static final Duration ZERO = new Duration(0, 0); // 各项时间量为0的时间段
/**
* The number of seconds in the duration.
*/
private final long seconds; // 秒部件
/**
* The number of nanoseconds in the duration, expressed as a fraction of the
* number of seconds. This is always positive, and never exceeds 999,999,999.
*/
private final int nanos; // 纳秒部件
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Constructs an instance of {@code Duration} using seconds and nanoseconds.
*
* @param seconds the length of the duration in seconds, positive or negative
* @param nanos the nanoseconds within the second, from 0 to 999,999,999
*/
private Duration(long seconds, int nanos) {
super();
this.seconds = seconds;
this.nanos = nanos;
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 工厂方法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Obtains a {@code Duration} representing a number of standard 24 hour days.
* <p>
* The seconds are calculated based on the standard definition of a day,
* where each day is 86400 seconds which implies a 24 hour day.
* The nanosecond in second field is set to zero.
*
* @param days the number of days, positive or negative
*
* @return a {@code Duration}, not null
*
* @throws ArithmeticException if the input days exceeds the capacity of {@code Duration}
*/
// 返回由"天"构造的时间段
public static Duration ofDays(long days) {
// 获取days天包含的秒数
long seconds = Math.multiplyExact(days, SECONDS_PER_DAY);
return create(seconds, 0);
}
/**
* Obtains a {@code Duration} representing a number of standard hours.
* <p>
* The seconds are calculated based on the standard definition of an hour,
* where each hour is 3600 seconds.
* The nanosecond in second field is set to zero.
*
* @param hours the number of hours, positive or negative
*
* @return a {@code Duration}, not null
*
* @throws ArithmeticException if the input hours exceeds the capacity of {@code Duration}
*/
// 返回由"小时"构造的时间段
public static Duration ofHours(long hours) {
// 获取hours小时包含的秒数
long seconds = Math.multiplyExact(hours, SECONDS_PER_HOUR);
return create(seconds, 0);
}
/**
* Obtains a {@code Duration} representing a number of standard minutes.
* <p>
* The seconds are calculated based on the standard definition of a minute,
* where each minute is 60 seconds.
* The nanosecond in second field is set to zero.
*
* @param minutes the number of minutes, positive or negative
*
* @return a {@code Duration}, not null
*
* @throws ArithmeticException if the input minutes exceeds the capacity of {@code Duration}
*/
// 返回由"分钟"构造的时间段
public static Duration ofMinutes(long minutes) {
// 获取minutes分包含的秒数
long seconds = Math.multiplyExact(minutes, SECONDS_PER_MINUTE);
return create(seconds, 0);
}
/**
* Obtains a {@code Duration} representing a number of seconds.
* <p>
* The nanosecond in second field is set to zero.
*
* @param seconds the number of seconds, positive or negative
*
* @return a {@code Duration}, not null
*/
// 返回由"秒"构造的时间段
public static Duration ofSeconds(long seconds) {
return create(seconds, 0);
}
/**
* Obtains a {@code Duration} representing a number of seconds and an
* adjustment in nanoseconds.
* <p>
* This method allows an arbitrary number of nanoseconds to be passed in.
* The factory will alter the values of the second and nanosecond in order
* to ensure that the stored nanosecond is in the range 0 to 999,999,999.
* For example, the following will result in exactly the same duration:
* <pre>
* Duration.ofSeconds(3, 1);
* Duration.ofSeconds(4, -999_999_999);
* Duration.ofSeconds(2, 1000_000_001);
* </pre>
*
* @param seconds the number of seconds, positive or negative
* @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative
*
* @return a {@code Duration}, not null
*
* @throws ArithmeticException if the adjustment causes the seconds to exceed the capacity of {@code Duration}
*/
// 返回由"秒"和"纳秒"构造的时间段
public static Duration ofSeconds(long seconds, long nanoAdjustment) {
long secs = Math.addExact(seconds, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
int nos = (int) Math.floorMod(nanoAdjustment, NANOS_PER_SECOND);
return create(secs, nos);
}
/**
* Obtains a {@code Duration} representing a number of milliseconds.
* <p>
* The seconds and nanoseconds are extracted from the specified milliseconds.
*
* @param millis the number of milliseconds, positive or negative
*
* @return a {@code Duration}, not null
*/
// 返回由"毫秒"构造的时间段
public static Duration ofMillis(long millis) {
long secs = millis / 1000;
int mos = (int) (millis % 1000);
if(mos<0) {
mos += 1000;
secs--;
}
return create(secs, mos * 1000_000);
}
/**
* Obtains a {@code Duration} representing a number of nanoseconds.
* <p>
* The seconds and nanoseconds are extracted from the specified nanoseconds.
*
* @param nanos the number of nanoseconds, positive or negative
*
* @return a {@code Duration}, not null
*/
// 返回由"纳秒"构造的时间段
public static Duration ofNanos(long nanos) {
long secs = nanos / NANOS_PER_SECOND;
int nos = (int) (nanos % NANOS_PER_SECOND);
if(nos<0) {
nos += NANOS_PER_SECOND;
secs--;
}
return create(secs, nos);
}
/**
* Obtains a {@code Duration} representing an amount in the specified unit.
* <p>
* The parameters represent the two parts of a phrase like '6 Hours'. For example:
* <pre>
* Duration.of(3, SECONDS);
* Duration.of(465, HOURS);
* </pre>
* Only a subset of units are accepted by this method.
* The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or
* be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
*
* @param amount the amount of the duration, measured in terms of the unit, positive or negative
* @param unit the unit that the duration is measured in, must have an exact duration, not null
*
* @return a {@code Duration}, not null
*
* @throws DateTimeException if the period unit has an estimated duration
* @throws ArithmeticException if a numeric overflow occurs
*/
// 返回由amount个unit单位的时间量构造的时间段
public static Duration of(long amount, TemporalUnit unit) {
return ZERO.plus(amount, unit);
}
/**
* Obtains an instance of {@code Duration} from a temporal amount.
* <p>
* This obtains a duration based on the specified amount.
* A {@code TemporalAmount} represents an amount of time, which may be
* date-based or time-based, which this factory extracts to a duration.
* <p>
* The conversion loops around the set of units from the amount and uses
* the {@linkplain TemporalUnit#getDuration() duration} of the unit to
* calculate the total {@code Duration}.
* Only a subset of units are accepted by this method. The unit must either
* have an {@linkplain TemporalUnit#isDurationEstimated() exact duration}
* or be {@link ChronoUnit#DAYS} which is treated as 24 hours.
* If any other units are found then an exception is thrown.
*
* @param amount the temporal amount to convert, not null
*
* @return the equivalent duration, not null
*
* @throws DateTimeException if unable to convert to a {@code Duration}
* @throws ArithmeticException if numeric overflow occurs
*/
// 将指定的"时间段"转换为Duration
public static Duration from(TemporalAmount amount) {
Objects.requireNonNull(amount, "amount");
Duration duration = ZERO;
// 获取"时间段"amount内包含的时间量单位
List<TemporalUnit> temporalUnits = amount.getUnits();
// 遍历所有时间量单位
for(TemporalUnit unit : temporalUnits) {
// 获取"时间段"amount中指定的时间量单位unit对应的时间量数值
long amountToAdd = amount.get(unit);
// 将该时间量累加到ZERO上
duration = duration.plus(amountToAdd, unit);
}
return duration;
}
/**
* Obtains a {@code Duration} from a text string such as {@code PnDTnHnMn.nS}.
* <p>
* This will parse a textual representation of a duration, including the
* string produced by {@code toString()}. The formats accepted are based
* on the ISO-8601 duration format {@code PnDTnHnMn.nS} with days
* considered to be exactly 24 hours.
* <p>
* The string starts with an optional sign, denoted by the ASCII negative
* or positive symbol. If negative, the whole period is negated.
* The ASCII letter "P" is next in upper or lower case.
* There are then four sections, each consisting of a number and a suffix.
* The sections have suffixes in ASCII of "D", "H", "M" and "S" for
* days, hours, minutes and seconds, accepted in upper or lower case.
* The suffixes must occur in order. The ASCII letter "T" must occur before
* the first occurrence, if any, of an hour, minute or second section.
* At least one of the four sections must be present, and if "T" is present
* there must be at least one section after the "T".
* The number part of each section must consist of one or more ASCII digits.
* The number may be prefixed by the ASCII negative or positive symbol.
* The number of days, hours and minutes must parse to a {@code long}.
* The number of seconds must parse to a {@code long} with optional fraction.
* The decimal point may be either a dot or a comma.
* The fractional part may have from zero to 9 digits.
* <p>
* The leading plus/minus sign, and negative values for other units are
* not part of the ISO-8601 standard.
* <p>
* Examples:
* <pre>
* "PT20.345S" -- parses as "20.345 seconds"
* "PT15M" -- parses as "15 minutes" (where a minute is 60 seconds)
* "PT10H" -- parses as "10 hours" (where an hour is 3600 seconds)
* "P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
* "P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes"
* "PT-6H3M" -- parses as "-6 hours and +3 minutes"
* "-PT6H3M" -- parses as "-6 hours and -3 minutes"
* "-PT-6H+3M" -- parses as "+6 hours and -3 minutes"
* </pre>
*
* @param text the text to parse, not null
*
* @return the parsed duration, not null
*
* @throws DateTimeParseException if the text cannot be parsed to a duration
*/
/*
* 从给定的文本中解析出一段时间信息,文本格式为"PnDTnHnMn.nS"。
*
* "PT20.345S" -> 20.345秒
* "PT15M" -> 15分
* "PT10H" -> 10小时
* "P2D" -> 2天
* "P2DT3H4M" -> 2天3小时4分
* "PT-6H3M" -> -6小时+3分
* "-PT6H3M" -> -6小时-3分
* "-PT-6H+3M" -> +6小时-3分
*/
public static Duration parse(CharSequence text) {
Objects.requireNonNull(text, "text");
Matcher matcher = Lazy.PATTERN.matcher(text);
if(matcher.matches()) {
// check for letter T but no time sections
if(!charMatch(text, matcher.start(3), matcher.end(3), 'T')) {
boolean negate = charMatch(text, matcher.start(1), matcher.end(1), '-');
int dayStart = matcher.start(2), dayEnd = matcher.end(2);
int hourStart = matcher.start(4), hourEnd = matcher.end(4);
int minuteStart = matcher.start(5), minuteEnd = matcher.end(5);
int secondStart = matcher.start(6), secondEnd = matcher.end(6);
int fractionStart = matcher.start(7), fractionEnd = matcher.end(7);
if(dayStart >= 0 || hourStart >= 0 || minuteStart >= 0 || secondStart >= 0) {
long daysAsSecs = parseNumber(text, dayStart, dayEnd, SECONDS_PER_DAY, "days");
long hoursAsSecs = parseNumber(text, hourStart, hourEnd, SECONDS_PER_HOUR, "hours");
long minsAsSecs = parseNumber(text, minuteStart, minuteEnd, SECONDS_PER_MINUTE, "minutes");
long seconds = parseNumber(text, secondStart, secondEnd, 1, "seconds");
boolean negativeSecs = secondStart >= 0 && text.charAt(secondStart) == '-';
int nanos = parseFraction(text, fractionStart, fractionEnd, negativeSecs ? -1 : 1);
try {
return create(negate, daysAsSecs, hoursAsSecs, minsAsSecs, seconds, nanos);
} catch(ArithmeticException ex) {
throw new DateTimeParseException("Text cannot be parsed to a Duration: overflow", text, 0, ex);
}
}
}
}
throw new DateTimeParseException("Text cannot be parsed to a Duration", text, 0);
}
/*▲ 工厂方法 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 转换 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Gets the number of days in this duration.
* <p>
* This returns the total number of days in the duration by dividing the
* number of seconds by 86400.
* This is based on the standard definition of a day as 24 hours.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @return the number of days in the duration, may be negative
*/
// 返回当前"时间段"包含的天数
public long toDays() {
return seconds / SECONDS_PER_DAY;
}
/**
* Gets the number of hours in this duration.
* <p>
* This returns the total number of hours in the duration by dividing the
* number of seconds by 3600.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @return the number of hours in the duration, may be negative
*/
// 返回当前"时间段"包含的小时数
public long toHours() {
return seconds / SECONDS_PER_HOUR;
}
/**
* Gets the number of minutes in this duration.
* <p>
* This returns the total number of minutes in the duration by dividing the
* number of seconds by 60.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @return the number of minutes in the duration, may be negative
*/
// 返回当前"时间段"包含的分钟数
public long toMinutes() {
return seconds / SECONDS_PER_MINUTE;
}
/**
* Gets the number of seconds in this duration.
* <p>
* This returns the total number of whole seconds in the duration.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @return the whole seconds part of the length of the duration, positive or negative
*
* @since 9
*/
// 返回当前"时间段"包含的秒数
public long toSeconds() {
return seconds;
}
/**
* Converts this duration to the total length in milliseconds.
* <p>
* If this duration is too large to fit in a {@code long} milliseconds, then an
* exception is thrown.
* <p>
* If this duration has greater than millisecond precision, then the conversion
* will drop any excess precision information as though the amount in nanoseconds
* was subject to integer division by one million.
*
* @return the total length of the duration in milliseconds
*
* @throws ArithmeticException if numeric overflow occurs
*/
// 返回当前"时间段"包含的毫秒数
public long toMillis() {
long tempSeconds = seconds;
long tempNanos = nanos;
if(tempSeconds<0) {
// change the seconds and nano value to
// handle Long.MIN_VALUE case
tempSeconds = tempSeconds + 1;
tempNanos = tempNanos - NANOS_PER_SECOND;
}
long millis = Math.multiplyExact(tempSeconds, 1000);
millis = Math.addExact(millis, tempNanos / NANOS_PER_MILLI);
return millis;
}
/**
* Converts this duration to the total length in nanoseconds expressed as a {@code long}.
* <p>
* If this duration is too large to fit in a {@code long} nanoseconds, then an
* exception is thrown.
*
* @return the total length of the duration in nanoseconds
*
* @throws ArithmeticException if numeric overflow occurs
*/
// 返回当前"时间段"包含的纳秒数
public long toNanos() {
long tempSeconds = seconds;
long tempNanos = nanos;
if(tempSeconds<0) {
// change the seconds and nano value to
// handle Long.MIN_VALUE case
tempSeconds = tempSeconds + 1;
tempNanos = tempNanos - NANOS_PER_SECOND;
}
long totalNanos = Math.multiplyExact(tempSeconds, NANOS_PER_SECOND);
totalNanos = Math.addExact(totalNanos, tempNanos);
return totalNanos;
}
/*
* // 2天3小时4分5秒6毫秒
* Duration duration = Duration.parse("P2DT3H4M5.006S");
* System.out.println(duration);
*
* System.out.println(duration.toDaysPart()); // 2
* System.out.println(duration.toHoursPart()); // 3
* System.out.println(duration.toMinutesPart()); // 4
* System.out.println(duration.toSecondsPart()); // 5
* System.out.println(duration.toMillisPart()); // 6
*/
/**
* Extracts the number of days in the duration.
* <p>
* This returns the total number of days in the duration by dividing the
* number of seconds by 86400.
* This is based on the standard definition of a day as 24 hours.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @return the number of days in the duration, may be negative
*
* @since 9
*/
// 将当前"时间段"转换为"天"部件
public long toDaysPart() {
return seconds / SECONDS_PER_DAY;
}
/**
* Extracts the number of hours part in the duration.
* <p>
* This returns the number of remaining hours when dividing {@link #toHours}
* by hours in a day.
* This is based on the standard definition of a day as 24 hours.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @return the number of hours part in the duration, may be negative
*
* @since 9
*/
// 将当前"时间段"转换为"天"部件
public int toHoursPart() {
return (int) (toHours() % 24);
}
/**
* Extracts the number of minutes part in the duration.
* <p>
* This returns the number of remaining minutes when dividing {@link #toMinutes}
* by minutes in an hour.
* This is based on the standard definition of an hour as 60 minutes.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @return the number of minutes parts in the duration, may be negative
*
* @since 9
*/
// 将当前"时间段"转换为"分钟"部件
public int toMinutesPart() {
return (int) (toMinutes() % MINUTES_PER_HOUR);
}
/**
* Extracts the number of seconds part in the duration.
* <p>
* This returns the remaining seconds when dividing {@link #toSeconds}
* by seconds in a minute.
* This is based on the standard definition of a minute as 60 seconds.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @return the number of seconds parts in the duration, may be negative
*
* @since 9
*/
// 将当前"时间段"转换为"秒"部件
public int toSecondsPart() {
return (int) (seconds % SECONDS_PER_MINUTE);
}
/**
* Extracts the number of milliseconds part of the duration.
* <p>
* This returns the milliseconds part by dividing the number of nanoseconds by 1,000,000.
* The length of the duration is stored using two fields - seconds and nanoseconds.
* The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to
* the length in seconds.
* The total duration is defined by calling {@link #getNano()} and {@link #getSeconds()}.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @return the number of milliseconds part of the duration.
*
* @since 9
*/
// 将当前"时间段"转换为"毫秒"部件(注:"毫秒"部件与"纳秒"部件通常不一起使用)
public int toMillisPart() {
return nanos / 1000_000;
}
/**
* Get the nanoseconds part within seconds of the duration.
* <p>
* The length of the duration is stored using two fields - seconds and nanoseconds.
* The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to
* the length in seconds.
* The total duration is defined by calling {@link #getNano()} and {@link #getSeconds()}.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999
*
* @since 9
*/
// 将当前"时间段"转换为"纳秒"部件(注:"毫秒"部件与"纳秒"部件通常不一起使用)
public int toNanosPart() {
return nanos;
}
/*▲ 转换 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 部件 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Gets the number of seconds in this duration.
* <p>
* The length of the duration is stored using two fields - seconds and nanoseconds.
* The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to
* the length in seconds.
* The total duration is defined by calling this method and {@link #getNano()}.
* <p>
* A {@code Duration} represents a directed distance between two points on the time-line.
* A negative duration is expressed by the negative sign of the seconds part.
* A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds.
*
* @return the whole seconds part of the length of the duration, positive or negative
*/
// 返回秒部件的值
public long getSeconds() {
return seconds;
}
/**
* Gets the number of nanoseconds within the second in this duration.
* <p>
* The length of the duration is stored using two fields - seconds and nanoseconds.
* The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to
* the length in seconds.
* The total duration is defined by calling this method and {@link #getSeconds()}.
* <p>
* A {@code Duration} represents a directed distance between two points on the time-line.
* A negative duration is expressed by the negative sign of the seconds part.
* A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds.
*
* @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999
*/
// 返回纳秒部件的值
public int getNano() {
return nanos;
}
/*▲ 部件 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 加法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a copy of this duration with the specified duration added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param duration the duration to add, positive or negative, not null
*
* @return a {@code Duration} based on this duration with the specified duration added, not null
*
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 对当前"时间段"的值与参数中的"时间段"求和
*
* 如果求和后的值与当前"时间段"的值相等,则直接返回当前"时间段"对象。
* 否则,需要构造"求和"后的新对象再返回。
*/
public Duration plus(Duration duration) {
return plus(duration.getSeconds(), duration.getNano());
}
/**
* Returns a copy of this duration with the specified duration added.
* <p>
* The duration amount is measured in terms of the specified unit.
* Only a subset of units are accepted by this method.
* The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or
* be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToAdd the amount to add, measured in terms of the unit, positive or negative
* @param unit the unit that the amount is measured in, must have an exact duration, not null
*
* @return a {@code Duration} based on this duration with the specified duration added, not null
*
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 对当前"时间段"的值累加amountToAdd个unit单位的时间量
*
* 如果累加后的值与当前"时间段"的值相等,则直接返回当前"时间段"对象。
* 否则,需要构造"累加"操作后的新对象再返回。
*/
public Duration plus(long amountToAdd, TemporalUnit unit) {
Objects.requireNonNull(unit, "unit");
if(unit == DAYS) {
return plus(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY), 0);
}
// 要求unit具备精确的秒数,即必须为"时间"单位,而不能是"日期"单位
if(unit.isDurationEstimated()) {
throw new UnsupportedTemporalTypeException("Unit must not have an estimated duration");
}
if(amountToAdd == 0) {
return this;
}
// 单位换算
if(unit instanceof ChronoUnit) {
switch((ChronoUnit) unit) {
case NANOS:
return plusNanos(amountToAdd);
case MICROS:
return plusSeconds((amountToAdd / (1000_000L * 1000)) * 1000).plusNanos((amountToAdd % (1000_000L * 1000)) * 1000);
case MILLIS:
return plusMillis(amountToAdd);
case SECONDS:
return plusSeconds(amountToAdd);
}
// 如果是MINUTES、HOURS、HALF_DAYS,则需要计算amountToAdd个该单位代表多少秒
long duration = Math.multiplyExact(unit.getDuration().seconds, amountToAdd);
return plusSeconds(duration);
}
// 计算需要累加的Duration值:每个unit代表的Duration * unit的数量
Duration duration = unit.getDuration().multipliedBy(amountToAdd);
// 先加秒再加纳秒
return plusSeconds(duration.getSeconds()).plusNanos(duration.getNano());
}
/**
* Returns a copy of this duration with the specified duration in standard 24 hour days added.
* <p>
* The number of days is multiplied by 86400 to obtain the number of seconds to add.
* This is based on the standard definition of a day as 24 hours.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param daysToAdd the days to add, positive or negative
*
* @return a {@code Duration} based on this duration with the specified days added, not null
*
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 在当前"时间段"的值上累加daysToAdd天
*
* 如果累加后的值与当前"时间段"的值相等,则直接返回当前"时间段"对象。
* 否则,需要构造"累加"操作后的新对象再返回。
*/
public Duration plusDays(long daysToAdd) {
return plus(Math.multiplyExact(daysToAdd, SECONDS_PER_DAY), 0);
}
/**
* Returns a copy of this duration with the specified duration in hours added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param hoursToAdd the hours to add, positive or negative
*
* @return a {@code Duration} based on this duration with the specified hours added, not null
*
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 在当前"时间段"的值上累加hoursToAdd小时
*
* 如果累加后的值与当前"时间段"的值相等,则直接返回当前"时间段"对象。
* 否则,需要构造"累加"操作后的新对象再返回。
*/
public Duration plusHours(long hoursToAdd) {
return plus(Math.multiplyExact(hoursToAdd, SECONDS_PER_HOUR), 0);
}
/**
* Returns a copy of this duration with the specified duration in minutes added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param minutesToAdd the minutes to add, positive or negative
*
* @return a {@code Duration} based on this duration with the specified minutes added, not null
*
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 在当前"时间段"的值上累加minutesToAdd分钟
*
* 如果累加后的值与当前"时间段"的值相等,则直接返回当前"时间段"对象。
* 否则,需要构造"累加"操作后的新对象再返回。
*/
public Duration plusMinutes(long minutesToAdd) {
return plus(Math.multiplyExact(minutesToAdd, SECONDS_PER_MINUTE), 0);
}
/**
* Returns a copy of this duration with the specified duration in seconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param secondsToAdd the seconds to add, positive or negative
*
* @return a {@code Duration} based on this duration with the specified seconds added, not null
*
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 在当前"时间段"的值上累加secondsToAdd秒
*
* 如果累加后的值与当前"时间段"的值相等,则直接返回当前"时间段"对象。
* 否则,需要构造"累加"操作后的新对象再返回。
*/
public Duration plusSeconds(long secondsToAdd) {
return plus(secondsToAdd, 0);
}
/**
* Returns a copy of this duration with the specified duration in milliseconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param millisToAdd the milliseconds to add, positive or negative
*
* @return a {@code Duration} based on this duration with the specified milliseconds added, not null
*
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 在当前"时间段"的值上累加millisToAdd毫秒
*
* 如果累加后的值与当前"时间段"的值相等,则直接返回当前"时间段"对象。
* 否则,需要构造"累加"操作后的新对象再返回。
*/
public Duration plusMillis(long millisToAdd) {
return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000);
}
/**
* Returns a copy of this duration with the specified duration in nanoseconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param nanosToAdd the nanoseconds to add, positive or negative
*
* @return a {@code Duration} based on this duration with the specified nanoseconds added, not null
*
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 在当前"时间段"的值上累加nanosToAdd纳秒
*
* 如果累加后的值与当前"时间段"的值相等,则直接返回当前"时间段"对象。
* 否则,需要构造"累加"操作后的新对象再返回。
*/
public Duration plusNanos(long nanosToAdd) {
return plus(0, nanosToAdd);
}
/*▲ 加法 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 减法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a copy of this duration with the specified duration subtracted.
* <p>
* This instance is immutable and unaffected by this method call.