Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/Period.java
38829 views
1
/*
2
* Copyright (c) 2012, 2015, 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) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
33
*
34
* All rights reserved.
35
*
36
* Redistribution and use in source and binary forms, with or without
37
* modification, are permitted provided that the following conditions are met:
38
*
39
* * Redistributions of source code must retain the above copyright notice,
40
* this list of conditions and the following disclaimer.
41
*
42
* * Redistributions in binary form must reproduce the above copyright notice,
43
* this list of conditions and the following disclaimer in the documentation
44
* and/or other materials provided with the distribution.
45
*
46
* * Neither the name of JSR-310 nor the names of its contributors
47
* may be used to endorse or promote products derived from this software
48
* without specific prior written permission.
49
*
50
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
51
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
52
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
53
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
54
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
55
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
56
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
57
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
58
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
59
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
60
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61
*/
62
package java.time;
63
64
import static java.time.temporal.ChronoUnit.DAYS;
65
import static java.time.temporal.ChronoUnit.MONTHS;
66
import static java.time.temporal.ChronoUnit.YEARS;
67
68
import java.io.DataInput;
69
import java.io.DataOutput;
70
import java.io.IOException;
71
import java.io.InvalidObjectException;
72
import java.io.ObjectInputStream;
73
import java.io.Serializable;
74
import java.time.chrono.ChronoLocalDate;
75
import java.time.chrono.ChronoPeriod;
76
import java.time.chrono.Chronology;
77
import java.time.chrono.IsoChronology;
78
import java.time.format.DateTimeParseException;
79
import java.time.temporal.ChronoUnit;
80
import java.time.temporal.Temporal;
81
import java.time.temporal.TemporalAccessor;
82
import java.time.temporal.TemporalAmount;
83
import java.time.temporal.TemporalQueries;
84
import java.time.temporal.TemporalUnit;
85
import java.time.temporal.UnsupportedTemporalTypeException;
86
import java.util.Arrays;
87
import java.util.Collections;
88
import java.util.List;
89
import java.util.Objects;
90
import java.util.regex.Matcher;
91
import java.util.regex.Pattern;
92
93
/**
94
* A date-based amount of time in the ISO-8601 calendar system,
95
* such as '2 years, 3 months and 4 days'.
96
* <p>
97
* This class models a quantity or amount of time in terms of years, months and days.
98
* See {@link Duration} for the time-based equivalent to this class.
99
* <p>
100
* Durations and periods differ in their treatment of daylight savings time
101
* when added to {@link ZonedDateTime}. A {@code Duration} will add an exact
102
* number of seconds, thus a duration of one day is always exactly 24 hours.
103
* By contrast, a {@code Period} will add a conceptual day, trying to maintain
104
* the local time.
105
* <p>
106
* For example, consider adding a period of one day and a duration of one day to
107
* 18:00 on the evening before a daylight savings gap. The {@code Period} will add
108
* the conceptual day and result in a {@code ZonedDateTime} at 18:00 the following day.
109
* By contrast, the {@code Duration} will add exactly 24 hours, resulting in a
110
* {@code ZonedDateTime} at 19:00 the following day (assuming a one hour DST gap).
111
* <p>
112
* The supported units of a period are {@link ChronoUnit#YEARS YEARS},
113
* {@link ChronoUnit#MONTHS MONTHS} and {@link ChronoUnit#DAYS DAYS}.
114
* All three fields are always present, but may be set to zero.
115
* <p>
116
* The ISO-8601 calendar system is the modern civil calendar system used today
117
* in most of the world. It is equivalent to the proleptic Gregorian calendar
118
* system, in which today's rules for leap years are applied for all time.
119
* <p>
120
* The period is modeled as a directed amount of time, meaning that individual parts of the
121
* period may be negative.
122
*
123
* <p>
124
* This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>
125
* class; use of identity-sensitive operations (including reference equality
126
* ({@code ==}), identity hash code, or synchronization) on instances of
127
* {@code Period} may have unpredictable results and should be avoided.
128
* The {@code equals} method should be used for comparisons.
129
*
130
* @implSpec
131
* This class is immutable and thread-safe.
132
*
133
* @since 1.8
134
*/
135
public final class Period
136
implements ChronoPeriod, Serializable {
137
138
/**
139
* A constant for a period of zero.
140
*/
141
public static final Period ZERO = new Period(0, 0, 0);
142
/**
143
* Serialization version.
144
*/
145
private static final long serialVersionUID = -3587258372562876L;
146
/**
147
* The pattern for parsing.
148
*/
149
private static final Pattern PATTERN =
150
Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)Y)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)W)?(?:([-+]?[0-9]+)D)?", Pattern.CASE_INSENSITIVE);
151
152
/**
153
* The set of supported units.
154
*/
155
private static final List<TemporalUnit> SUPPORTED_UNITS =
156
Collections.unmodifiableList(Arrays.<TemporalUnit>asList(YEARS, MONTHS, DAYS));
157
158
/**
159
* The number of years.
160
*/
161
private final int years;
162
/**
163
* The number of months.
164
*/
165
private final int months;
166
/**
167
* The number of days.
168
*/
169
private final int days;
170
171
//-----------------------------------------------------------------------
172
/**
173
* Obtains a {@code Period} representing a number of years.
174
* <p>
175
* The resulting period will have the specified years.
176
* The months and days units will be zero.
177
*
178
* @param years the number of years, positive or negative
179
* @return the period of years, not null
180
*/
181
public static Period ofYears(int years) {
182
return create(years, 0, 0);
183
}
184
185
/**
186
* Obtains a {@code Period} representing a number of months.
187
* <p>
188
* The resulting period will have the specified months.
189
* The years and days units will be zero.
190
*
191
* @param months the number of months, positive or negative
192
* @return the period of months, not null
193
*/
194
public static Period ofMonths(int months) {
195
return create(0, months, 0);
196
}
197
198
/**
199
* Obtains a {@code Period} representing a number of weeks.
200
* <p>
201
* The resulting period will be day-based, with the amount of days
202
* equal to the number of weeks multiplied by 7.
203
* The years and months units will be zero.
204
*
205
* @param weeks the number of weeks, positive or negative
206
* @return the period, with the input weeks converted to days, not null
207
*/
208
public static Period ofWeeks(int weeks) {
209
return create(0, 0, Math.multiplyExact(weeks, 7));
210
}
211
212
/**
213
* Obtains a {@code Period} representing a number of days.
214
* <p>
215
* The resulting period will have the specified days.
216
* The years and months units will be zero.
217
*
218
* @param days the number of days, positive or negative
219
* @return the period of days, not null
220
*/
221
public static Period ofDays(int days) {
222
return create(0, 0, days);
223
}
224
225
//-----------------------------------------------------------------------
226
/**
227
* Obtains a {@code Period} representing a number of years, months and days.
228
* <p>
229
* This creates an instance based on years, months and days.
230
*
231
* @param years the amount of years, may be negative
232
* @param months the amount of months, may be negative
233
* @param days the amount of days, may be negative
234
* @return the period of years, months and days, not null
235
*/
236
public static Period of(int years, int months, int days) {
237
return create(years, months, days);
238
}
239
240
//-----------------------------------------------------------------------
241
/**
242
* Obtains an instance of {@code Period} from a temporal amount.
243
* <p>
244
* This obtains a period based on the specified amount.
245
* A {@code TemporalAmount} represents an amount of time, which may be
246
* date-based or time-based, which this factory extracts to a {@code Period}.
247
* <p>
248
* The conversion loops around the set of units from the amount and uses
249
* the {@link ChronoUnit#YEARS YEARS}, {@link ChronoUnit#MONTHS MONTHS}
250
* and {@link ChronoUnit#DAYS DAYS} units to create a period.
251
* If any other units are found then an exception is thrown.
252
* <p>
253
* If the amount is a {@code ChronoPeriod} then it must use the ISO chronology.
254
*
255
* @param amount the temporal amount to convert, not null
256
* @return the equivalent period, not null
257
* @throws DateTimeException if unable to convert to a {@code Period}
258
* @throws ArithmeticException if the amount of years, months or days exceeds an int
259
*/
260
public static Period from(TemporalAmount amount) {
261
if (amount instanceof Period) {
262
return (Period) amount;
263
}
264
if (amount instanceof ChronoPeriod) {
265
if (IsoChronology.INSTANCE.equals(((ChronoPeriod) amount).getChronology()) == false) {
266
throw new DateTimeException("Period requires ISO chronology: " + amount);
267
}
268
}
269
Objects.requireNonNull(amount, "amount");
270
int years = 0;
271
int months = 0;
272
int days = 0;
273
for (TemporalUnit unit : amount.getUnits()) {
274
long unitAmount = amount.get(unit);
275
if (unit == ChronoUnit.YEARS) {
276
years = Math.toIntExact(unitAmount);
277
} else if (unit == ChronoUnit.MONTHS) {
278
months = Math.toIntExact(unitAmount);
279
} else if (unit == ChronoUnit.DAYS) {
280
days = Math.toIntExact(unitAmount);
281
} else {
282
throw new DateTimeException("Unit must be Years, Months or Days, but was " + unit);
283
}
284
}
285
return create(years, months, days);
286
}
287
288
//-----------------------------------------------------------------------
289
/**
290
* Obtains a {@code Period} from a text string such as {@code PnYnMnD}.
291
* <p>
292
* This will parse the string produced by {@code toString()} which is
293
* based on the ISO-8601 period formats {@code PnYnMnD} and {@code PnW}.
294
* <p>
295
* The string starts with an optional sign, denoted by the ASCII negative
296
* or positive symbol. If negative, the whole period is negated.
297
* The ASCII letter "P" is next in upper or lower case.
298
* There are then four sections, each consisting of a number and a suffix.
299
* At least one of the four sections must be present.
300
* The sections have suffixes in ASCII of "Y", "M", "W" and "D" for
301
* years, months, weeks and days, accepted in upper or lower case.
302
* The suffixes must occur in order.
303
* The number part of each section must consist of ASCII digits.
304
* The number may be prefixed by the ASCII negative or positive symbol.
305
* The number must parse to an {@code int}.
306
* <p>
307
* The leading plus/minus sign, and negative values for other units are
308
* not part of the ISO-8601 standard. In addition, ISO-8601 does not
309
* permit mixing between the {@code PnYnMnD} and {@code PnW} formats.
310
* Any week-based input is multiplied by 7 and treated as a number of days.
311
* <p>
312
* For example, the following are valid inputs:
313
* <pre>
314
* "P2Y" -- Period.ofYears(2)
315
* "P3M" -- Period.ofMonths(3)
316
* "P4W" -- Period.ofWeeks(4)
317
* "P5D" -- Period.ofDays(5)
318
* "P1Y2M3D" -- Period.of(1, 2, 3)
319
* "P1Y2M3W4D" -- Period.of(1, 2, 25)
320
* "P-1Y2M" -- Period.of(-1, 2, 0)
321
* "-P1Y2M" -- Period.of(-1, -2, 0)
322
* </pre>
323
*
324
* @param text the text to parse, not null
325
* @return the parsed period, not null
326
* @throws DateTimeParseException if the text cannot be parsed to a period
327
*/
328
public static Period parse(CharSequence text) {
329
Objects.requireNonNull(text, "text");
330
Matcher matcher = PATTERN.matcher(text);
331
if (matcher.matches()) {
332
int negate = ("-".equals(matcher.group(1)) ? -1 : 1);
333
String yearMatch = matcher.group(2);
334
String monthMatch = matcher.group(3);
335
String weekMatch = matcher.group(4);
336
String dayMatch = matcher.group(5);
337
if (yearMatch != null || monthMatch != null || dayMatch != null || weekMatch != null) {
338
try {
339
int years = parseNumber(text, yearMatch, negate);
340
int months = parseNumber(text, monthMatch, negate);
341
int weeks = parseNumber(text, weekMatch, negate);
342
int days = parseNumber(text, dayMatch, negate);
343
days = Math.addExact(days, Math.multiplyExact(weeks, 7));
344
return create(years, months, days);
345
} catch (NumberFormatException ex) {
346
throw new DateTimeParseException("Text cannot be parsed to a Period", text, 0, ex);
347
}
348
}
349
}
350
throw new DateTimeParseException("Text cannot be parsed to a Period", text, 0);
351
}
352
353
private static int parseNumber(CharSequence text, String str, int negate) {
354
if (str == null) {
355
return 0;
356
}
357
int val = Integer.parseInt(str);
358
try {
359
return Math.multiplyExact(val, negate);
360
} catch (ArithmeticException ex) {
361
throw new DateTimeParseException("Text cannot be parsed to a Period", text, 0, ex);
362
}
363
}
364
365
//-----------------------------------------------------------------------
366
/**
367
* Obtains a {@code Period} consisting of the number of years, months,
368
* and days between two dates.
369
* <p>
370
* The start date is included, but the end date is not.
371
* The period is calculated by removing complete months, then calculating
372
* the remaining number of days, adjusting to ensure that both have the same sign.
373
* The number of months is then split into years and months based on a 12 month year.
374
* A month is considered if the end day-of-month is greater than or equal to the start day-of-month.
375
* For example, from {@code 2010-01-15} to {@code 2011-03-18} is one year, two months and three days.
376
* <p>
377
* The result of this method can be a negative period if the end is before the start.
378
* The negative sign will be the same in each of year, month and day.
379
*
380
* @param startDateInclusive the start date, inclusive, not null
381
* @param endDateExclusive the end date, exclusive, not null
382
* @return the period between this date and the end date, not null
383
* @see ChronoLocalDate#until(ChronoLocalDate)
384
*/
385
public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive) {
386
return startDateInclusive.until(endDateExclusive);
387
}
388
389
//-----------------------------------------------------------------------
390
/**
391
* Creates an instance.
392
*
393
* @param years the amount
394
* @param months the amount
395
* @param days the amount
396
*/
397
private static Period create(int years, int months, int days) {
398
if ((years | months | days) == 0) {
399
return ZERO;
400
}
401
return new Period(years, months, days);
402
}
403
404
/**
405
* Constructor.
406
*
407
* @param years the amount
408
* @param months the amount
409
* @param days the amount
410
*/
411
private Period(int years, int months, int days) {
412
this.years = years;
413
this.months = months;
414
this.days = days;
415
}
416
417
//-----------------------------------------------------------------------
418
/**
419
* Gets the value of the requested unit.
420
* <p>
421
* This returns a value for each of the three supported units,
422
* {@link ChronoUnit#YEARS YEARS}, {@link ChronoUnit#MONTHS MONTHS} and
423
* {@link ChronoUnit#DAYS DAYS}.
424
* All other units throw an exception.
425
*
426
* @param unit the {@code TemporalUnit} for which to return the value
427
* @return the long value of the unit
428
* @throws DateTimeException if the unit is not supported
429
* @throws UnsupportedTemporalTypeException if the unit is not supported
430
*/
431
@Override
432
public long get(TemporalUnit unit) {
433
if (unit == ChronoUnit.YEARS) {
434
return getYears();
435
} else if (unit == ChronoUnit.MONTHS) {
436
return getMonths();
437
} else if (unit == ChronoUnit.DAYS) {
438
return getDays();
439
} else {
440
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
441
}
442
}
443
444
/**
445
* Gets the set of units supported by this period.
446
* <p>
447
* The supported units are {@link ChronoUnit#YEARS YEARS},
448
* {@link ChronoUnit#MONTHS MONTHS} and {@link ChronoUnit#DAYS DAYS}.
449
* They are returned in the order years, months, days.
450
* <p>
451
* This set can be used in conjunction with {@link #get(TemporalUnit)}
452
* to access the entire state of the period.
453
*
454
* @return a list containing the years, months and days units, not null
455
*/
456
@Override
457
public List<TemporalUnit> getUnits() {
458
return SUPPORTED_UNITS;
459
}
460
461
/**
462
* Gets the chronology of this period, which is the ISO calendar system.
463
* <p>
464
* The {@code Chronology} represents the calendar system in use.
465
* The ISO-8601 calendar system is the modern civil calendar system used today
466
* in most of the world. It is equivalent to the proleptic Gregorian calendar
467
* system, in which today's rules for leap years are applied for all time.
468
*
469
* @return the ISO chronology, not null
470
*/
471
@Override
472
public IsoChronology getChronology() {
473
return IsoChronology.INSTANCE;
474
}
475
476
//-----------------------------------------------------------------------
477
/**
478
* Checks if all three units of this period are zero.
479
* <p>
480
* A zero period has the value zero for the years, months and days units.
481
*
482
* @return true if this period is zero-length
483
*/
484
public boolean isZero() {
485
return (this == ZERO);
486
}
487
488
/**
489
* Checks if any of the three units of this period are negative.
490
* <p>
491
* This checks whether the years, months or days units are less than zero.
492
*
493
* @return true if any unit of this period is negative
494
*/
495
public boolean isNegative() {
496
return years < 0 || months < 0 || days < 0;
497
}
498
499
//-----------------------------------------------------------------------
500
/**
501
* Gets the amount of years of this period.
502
* <p>
503
* This returns the years unit.
504
* <p>
505
* The months unit is not automatically normalized with the years unit.
506
* This means that a period of "15 months" is different to a period
507
* of "1 year and 3 months".
508
*
509
* @return the amount of years of this period, may be negative
510
*/
511
public int getYears() {
512
return years;
513
}
514
515
/**
516
* Gets the amount of months of this period.
517
* <p>
518
* This returns the months unit.
519
* <p>
520
* The months unit is not automatically normalized with the years unit.
521
* This means that a period of "15 months" is different to a period
522
* of "1 year and 3 months".
523
*
524
* @return the amount of months of this period, may be negative
525
*/
526
public int getMonths() {
527
return months;
528
}
529
530
/**
531
* Gets the amount of days of this period.
532
* <p>
533
* This returns the days unit.
534
*
535
* @return the amount of days of this period, may be negative
536
*/
537
public int getDays() {
538
return days;
539
}
540
541
//-----------------------------------------------------------------------
542
/**
543
* Returns a copy of this period with the specified amount of years.
544
* <p>
545
* This sets the amount of the years unit in a copy of this period.
546
* The months and days units are unaffected.
547
* <p>
548
* The months unit is not automatically normalized with the years unit.
549
* This means that a period of "15 months" is different to a period
550
* of "1 year and 3 months".
551
* <p>
552
* This instance is immutable and unaffected by this method call.
553
*
554
* @param years the years to represent, may be negative
555
* @return a {@code Period} based on this period with the requested years, not null
556
*/
557
public Period withYears(int years) {
558
if (years == this.years) {
559
return this;
560
}
561
return create(years, months, days);
562
}
563
564
/**
565
* Returns a copy of this period with the specified amount of months.
566
* <p>
567
* This sets the amount of the months unit in a copy of this period.
568
* The years and days units are unaffected.
569
* <p>
570
* The months unit is not automatically normalized with the years unit.
571
* This means that a period of "15 months" is different to a period
572
* of "1 year and 3 months".
573
* <p>
574
* This instance is immutable and unaffected by this method call.
575
*
576
* @param months the months to represent, may be negative
577
* @return a {@code Period} based on this period with the requested months, not null
578
*/
579
public Period withMonths(int months) {
580
if (months == this.months) {
581
return this;
582
}
583
return create(years, months, days);
584
}
585
586
/**
587
* Returns a copy of this period with the specified amount of days.
588
* <p>
589
* This sets the amount of the days unit in a copy of this period.
590
* The years and months units are unaffected.
591
* <p>
592
* This instance is immutable and unaffected by this method call.
593
*
594
* @param days the days to represent, may be negative
595
* @return a {@code Period} based on this period with the requested days, not null
596
*/
597
public Period withDays(int days) {
598
if (days == this.days) {
599
return this;
600
}
601
return create(years, months, days);
602
}
603
604
//-----------------------------------------------------------------------
605
/**
606
* Returns a copy of this period with the specified period added.
607
* <p>
608
* This operates separately on the years, months and days.
609
* No normalization is performed.
610
* <p>
611
* For example, "1 year, 6 months and 3 days" plus "2 years, 2 months and 2 days"
612
* returns "3 years, 8 months and 5 days".
613
* <p>
614
* The specified amount is typically an instance of {@code Period}.
615
* Other types are interpreted using {@link Period#from(TemporalAmount)}.
616
* <p>
617
* This instance is immutable and unaffected by this method call.
618
*
619
* @param amountToAdd the amount to add, not null
620
* @return a {@code Period} based on this period with the requested period added, not null
621
* @throws DateTimeException if the specified amount has a non-ISO chronology or
622
* contains an invalid unit
623
* @throws ArithmeticException if numeric overflow occurs
624
*/
625
public Period plus(TemporalAmount amountToAdd) {
626
Period isoAmount = Period.from(amountToAdd);
627
return create(
628
Math.addExact(years, isoAmount.years),
629
Math.addExact(months, isoAmount.months),
630
Math.addExact(days, isoAmount.days));
631
}
632
633
/**
634
* Returns a copy of this period with the specified years added.
635
* <p>
636
* This adds the amount to the years unit in a copy of this period.
637
* The months and days units are unaffected.
638
* For example, "1 year, 6 months and 3 days" plus 2 years returns "3 years, 6 months and 3 days".
639
* <p>
640
* This instance is immutable and unaffected by this method call.
641
*
642
* @param yearsToAdd the years to add, positive or negative
643
* @return a {@code Period} based on this period with the specified years added, not null
644
* @throws ArithmeticException if numeric overflow occurs
645
*/
646
public Period plusYears(long yearsToAdd) {
647
if (yearsToAdd == 0) {
648
return this;
649
}
650
return create(Math.toIntExact(Math.addExact(years, yearsToAdd)), months, days);
651
}
652
653
/**
654
* Returns a copy of this period with the specified months added.
655
* <p>
656
* This adds the amount to the months unit in a copy of this period.
657
* The years and days units are unaffected.
658
* For example, "1 year, 6 months and 3 days" plus 2 months returns "1 year, 8 months and 3 days".
659
* <p>
660
* This instance is immutable and unaffected by this method call.
661
*
662
* @param monthsToAdd the months to add, positive or negative
663
* @return a {@code Period} based on this period with the specified months added, not null
664
* @throws ArithmeticException if numeric overflow occurs
665
*/
666
public Period plusMonths(long monthsToAdd) {
667
if (monthsToAdd == 0) {
668
return this;
669
}
670
return create(years, Math.toIntExact(Math.addExact(months, monthsToAdd)), days);
671
}
672
673
/**
674
* Returns a copy of this period with the specified days added.
675
* <p>
676
* This adds the amount to the days unit in a copy of this period.
677
* The years and months units are unaffected.
678
* For example, "1 year, 6 months and 3 days" plus 2 days returns "1 year, 6 months and 5 days".
679
* <p>
680
* This instance is immutable and unaffected by this method call.
681
*
682
* @param daysToAdd the days to add, positive or negative
683
* @return a {@code Period} based on this period with the specified days added, not null
684
* @throws ArithmeticException if numeric overflow occurs
685
*/
686
public Period plusDays(long daysToAdd) {
687
if (daysToAdd == 0) {
688
return this;
689
}
690
return create(years, months, Math.toIntExact(Math.addExact(days, daysToAdd)));
691
}
692
693
//-----------------------------------------------------------------------
694
/**
695
* Returns a copy of this period with the specified period subtracted.
696
* <p>
697
* This operates separately on the years, months and days.
698
* No normalization is performed.
699
* <p>
700
* For example, "1 year, 6 months and 3 days" minus "2 years, 2 months and 2 days"
701
* returns "-1 years, 4 months and 1 day".
702
* <p>
703
* The specified amount is typically an instance of {@code Period}.
704
* Other types are interpreted using {@link Period#from(TemporalAmount)}.
705
* <p>
706
* This instance is immutable and unaffected by this method call.
707
*
708
* @param amountToSubtract the amount to subtract, not null
709
* @return a {@code Period} based on this period with the requested period subtracted, not null
710
* @throws DateTimeException if the specified amount has a non-ISO chronology or
711
* contains an invalid unit
712
* @throws ArithmeticException if numeric overflow occurs
713
*/
714
public Period minus(TemporalAmount amountToSubtract) {
715
Period isoAmount = Period.from(amountToSubtract);
716
return create(
717
Math.subtractExact(years, isoAmount.years),
718
Math.subtractExact(months, isoAmount.months),
719
Math.subtractExact(days, isoAmount.days));
720
}
721
722
/**
723
* Returns a copy of this period with the specified years subtracted.
724
* <p>
725
* This subtracts the amount from the years unit in a copy of this period.
726
* The months and days units are unaffected.
727
* For example, "1 year, 6 months and 3 days" minus 2 years returns "-1 years, 6 months and 3 days".
728
* <p>
729
* This instance is immutable and unaffected by this method call.
730
*
731
* @param yearsToSubtract the years to subtract, positive or negative
732
* @return a {@code Period} based on this period with the specified years subtracted, not null
733
* @throws ArithmeticException if numeric overflow occurs
734
*/
735
public Period minusYears(long yearsToSubtract) {
736
return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
737
}
738
739
/**
740
* Returns a copy of this period with the specified months subtracted.
741
* <p>
742
* This subtracts the amount from the months unit in a copy of this period.
743
* The years and days units are unaffected.
744
* For example, "1 year, 6 months and 3 days" minus 2 months returns "1 year, 4 months and 3 days".
745
* <p>
746
* This instance is immutable and unaffected by this method call.
747
*
748
* @param monthsToSubtract the years to subtract, positive or negative
749
* @return a {@code Period} based on this period with the specified months subtracted, not null
750
* @throws ArithmeticException if numeric overflow occurs
751
*/
752
public Period minusMonths(long monthsToSubtract) {
753
return (monthsToSubtract == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-monthsToSubtract));
754
}
755
756
/**
757
* Returns a copy of this period with the specified days subtracted.
758
* <p>
759
* This subtracts the amount from the days unit in a copy of this period.
760
* The years and months units are unaffected.
761
* For example, "1 year, 6 months and 3 days" minus 2 days returns "1 year, 6 months and 1 day".
762
* <p>
763
* This instance is immutable and unaffected by this method call.
764
*
765
* @param daysToSubtract the months to subtract, positive or negative
766
* @return a {@code Period} based on this period with the specified days subtracted, not null
767
* @throws ArithmeticException if numeric overflow occurs
768
*/
769
public Period minusDays(long daysToSubtract) {
770
return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract));
771
}
772
773
//-----------------------------------------------------------------------
774
/**
775
* Returns a new instance with each element in this period multiplied
776
* by the specified scalar.
777
* <p>
778
* This returns a period with each of the years, months and days units
779
* individually multiplied.
780
* For example, a period of "2 years, -3 months and 4 days" multiplied by
781
* 3 will return "6 years, -9 months and 12 days".
782
* No normalization is performed.
783
*
784
* @param scalar the scalar to multiply by, not null
785
* @return a {@code Period} based on this period with the amounts multiplied by the scalar, not null
786
* @throws ArithmeticException if numeric overflow occurs
787
*/
788
public Period multipliedBy(int scalar) {
789
if (this == ZERO || scalar == 1) {
790
return this;
791
}
792
return create(
793
Math.multiplyExact(years, scalar),
794
Math.multiplyExact(months, scalar),
795
Math.multiplyExact(days, scalar));
796
}
797
798
/**
799
* Returns a new instance with each amount in this period negated.
800
* <p>
801
* This returns a period with each of the years, months and days units
802
* individually negated.
803
* For example, a period of "2 years, -3 months and 4 days" will be
804
* negated to "-2 years, 3 months and -4 days".
805
* No normalization is performed.
806
*
807
* @return a {@code Period} based on this period with the amounts negated, not null
808
* @throws ArithmeticException if numeric overflow occurs, which only happens if
809
* one of the units has the value {@code Long.MIN_VALUE}
810
*/
811
public Period negated() {
812
return multipliedBy(-1);
813
}
814
815
//-----------------------------------------------------------------------
816
/**
817
* Returns a copy of this period with the years and months normalized.
818
* <p>
819
* This normalizes the years and months units, leaving the days unit unchanged.
820
* The months unit is adjusted to have an absolute value less than 11,
821
* with the years unit being adjusted to compensate. For example, a period of
822
* "1 Year and 15 months" will be normalized to "2 years and 3 months".
823
* <p>
824
* The sign of the years and months units will be the same after normalization.
825
* For example, a period of "1 year and -25 months" will be normalized to
826
* "-1 year and -1 month".
827
* <p>
828
* This instance is immutable and unaffected by this method call.
829
*
830
* @return a {@code Period} based on this period with excess months normalized to years, not null
831
* @throws ArithmeticException if numeric overflow occurs
832
*/
833
public Period normalized() {
834
long totalMonths = toTotalMonths();
835
long splitYears = totalMonths / 12;
836
int splitMonths = (int) (totalMonths % 12); // no overflow
837
if (splitYears == years && splitMonths == months) {
838
return this;
839
}
840
return create(Math.toIntExact(splitYears), splitMonths, days);
841
}
842
843
/**
844
* Gets the total number of months in this period.
845
* <p>
846
* This returns the total number of months in the period by multiplying the
847
* number of years by 12 and adding the number of months.
848
* <p>
849
* This instance is immutable and unaffected by this method call.
850
*
851
* @return the total number of months in the period, may be negative
852
*/
853
public long toTotalMonths() {
854
return years * 12L + months; // no overflow
855
}
856
857
//-------------------------------------------------------------------------
858
/**
859
* Adds this period to the specified temporal object.
860
* <p>
861
* This returns a temporal object of the same observable type as the input
862
* with this period added.
863
* If the temporal has a chronology, it must be the ISO chronology.
864
* <p>
865
* In most cases, it is clearer to reverse the calling pattern by using
866
* {@link Temporal#plus(TemporalAmount)}.
867
* <pre>
868
* // these two lines are equivalent, but the second approach is recommended
869
* dateTime = thisPeriod.addTo(dateTime);
870
* dateTime = dateTime.plus(thisPeriod);
871
* </pre>
872
* <p>
873
* The calculation operates as follows.
874
* First, the chronology of the temporal is checked to ensure it is ISO chronology or null.
875
* Second, if the months are zero, the years are added if non-zero, otherwise
876
* the combination of years and months is added if non-zero.
877
* Finally, any days are added.
878
* <p>
879
* This approach ensures that a partial period can be added to a partial date.
880
* For example, a period of years and/or months can be added to a {@code YearMonth},
881
* but a period including days cannot.
882
* The approach also adds years and months together when necessary, which ensures
883
* correct behaviour at the end of the month.
884
* <p>
885
* This instance is immutable and unaffected by this method call.
886
*
887
* @param temporal the temporal object to adjust, not null
888
* @return an object of the same type with the adjustment made, not null
889
* @throws DateTimeException if unable to add
890
* @throws ArithmeticException if numeric overflow occurs
891
*/
892
@Override
893
public Temporal addTo(Temporal temporal) {
894
validateChrono(temporal);
895
if (months == 0) {
896
if (years != 0) {
897
temporal = temporal.plus(years, YEARS);
898
}
899
} else {
900
long totalMonths = toTotalMonths();
901
if (totalMonths != 0) {
902
temporal = temporal.plus(totalMonths, MONTHS);
903
}
904
}
905
if (days != 0) {
906
temporal = temporal.plus(days, DAYS);
907
}
908
return temporal;
909
}
910
911
/**
912
* Subtracts this period from the specified temporal object.
913
* <p>
914
* This returns a temporal object of the same observable type as the input
915
* with this period subtracted.
916
* If the temporal has a chronology, it must be the ISO chronology.
917
* <p>
918
* In most cases, it is clearer to reverse the calling pattern by using
919
* {@link Temporal#minus(TemporalAmount)}.
920
* <pre>
921
* // these two lines are equivalent, but the second approach is recommended
922
* dateTime = thisPeriod.subtractFrom(dateTime);
923
* dateTime = dateTime.minus(thisPeriod);
924
* </pre>
925
* <p>
926
* The calculation operates as follows.
927
* First, the chronology of the temporal is checked to ensure it is ISO chronology or null.
928
* Second, if the months are zero, the years are subtracted if non-zero, otherwise
929
* the combination of years and months is subtracted if non-zero.
930
* Finally, any days are subtracted.
931
* <p>
932
* This approach ensures that a partial period can be subtracted from a partial date.
933
* For example, a period of years and/or months can be subtracted from a {@code YearMonth},
934
* but a period including days cannot.
935
* The approach also subtracts years and months together when necessary, which ensures
936
* correct behaviour at the end of the month.
937
* <p>
938
* This instance is immutable and unaffected by this method call.
939
*
940
* @param temporal the temporal object to adjust, not null
941
* @return an object of the same type with the adjustment made, not null
942
* @throws DateTimeException if unable to subtract
943
* @throws ArithmeticException if numeric overflow occurs
944
*/
945
@Override
946
public Temporal subtractFrom(Temporal temporal) {
947
validateChrono(temporal);
948
if (months == 0) {
949
if (years != 0) {
950
temporal = temporal.minus(years, YEARS);
951
}
952
} else {
953
long totalMonths = toTotalMonths();
954
if (totalMonths != 0) {
955
temporal = temporal.minus(totalMonths, MONTHS);
956
}
957
}
958
if (days != 0) {
959
temporal = temporal.minus(days, DAYS);
960
}
961
return temporal;
962
}
963
964
/**
965
* Validates that the temporal has the correct chronology.
966
*/
967
private void validateChrono(TemporalAccessor temporal) {
968
Objects.requireNonNull(temporal, "temporal");
969
Chronology temporalChrono = temporal.query(TemporalQueries.chronology());
970
if (temporalChrono != null && IsoChronology.INSTANCE.equals(temporalChrono) == false) {
971
throw new DateTimeException("Chronology mismatch, expected: ISO, actual: " + temporalChrono.getId());
972
}
973
}
974
975
//-----------------------------------------------------------------------
976
/**
977
* Checks if this period is equal to another period.
978
* <p>
979
* The comparison is based on the type {@code Period} and each of the three amounts.
980
* To be equal, the years, months and days units must be individually equal.
981
* Note that this means that a period of "15 Months" is not equal to a period
982
* of "1 Year and 3 Months".
983
*
984
* @param obj the object to check, null returns false
985
* @return true if this is equal to the other period
986
*/
987
@Override
988
public boolean equals(Object obj) {
989
if (this == obj) {
990
return true;
991
}
992
if (obj instanceof Period) {
993
Period other = (Period) obj;
994
return years == other.years &&
995
months == other.months &&
996
days == other.days;
997
}
998
return false;
999
}
1000
1001
/**
1002
* A hash code for this period.
1003
*
1004
* @return a suitable hash code
1005
*/
1006
@Override
1007
public int hashCode() {
1008
return years + Integer.rotateLeft(months, 8) + Integer.rotateLeft(days, 16);
1009
}
1010
1011
//-----------------------------------------------------------------------
1012
/**
1013
* Outputs this period as a {@code String}, such as {@code P6Y3M1D}.
1014
* <p>
1015
* The output will be in the ISO-8601 period format.
1016
* A zero period will be represented as zero days, 'P0D'.
1017
*
1018
* @return a string representation of this period, not null
1019
*/
1020
@Override
1021
public String toString() {
1022
if (this == ZERO) {
1023
return "P0D";
1024
} else {
1025
StringBuilder buf = new StringBuilder();
1026
buf.append('P');
1027
if (years != 0) {
1028
buf.append(years).append('Y');
1029
}
1030
if (months != 0) {
1031
buf.append(months).append('M');
1032
}
1033
if (days != 0) {
1034
buf.append(days).append('D');
1035
}
1036
return buf.toString();
1037
}
1038
}
1039
1040
//-----------------------------------------------------------------------
1041
/**
1042
* Writes the object using a
1043
* <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1044
* @serialData
1045
* <pre>
1046
* out.writeByte(14); // identifies a Period
1047
* out.writeInt(years);
1048
* out.writeInt(months);
1049
* out.writeInt(days);
1050
* </pre>
1051
*
1052
* @return the instance of {@code Ser}, not null
1053
*/
1054
private Object writeReplace() {
1055
return new Ser(Ser.PERIOD_TYPE, this);
1056
}
1057
1058
/**
1059
* Defend against malicious streams.
1060
*
1061
* @param s the stream to read
1062
* @throws java.io.InvalidObjectException always
1063
*/
1064
private void readObject(ObjectInputStream s) throws InvalidObjectException {
1065
throw new InvalidObjectException("Deserialization via serialization delegate");
1066
}
1067
1068
void writeExternal(DataOutput out) throws IOException {
1069
out.writeInt(years);
1070
out.writeInt(months);
1071
out.writeInt(days);
1072
}
1073
1074
static Period readExternal(DataInput in) throws IOException {
1075
int years = in.readInt();
1076
int months = in.readInt();
1077
int days = in.readInt();
1078
return Period.of(years, months, days);
1079
}
1080
1081
}
1082
1083