44 * and/or other materials provided with the distribution.
45 *
46 * * Neither the name of JSR-310 nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
51 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
52 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
53 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
54 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
55 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
56 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
57 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
58 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
59 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
60 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61 */
62 package java.time;
63
64 import static java.time.LocalTime.SECONDS_PER_DAY;
65 import static java.time.temporal.ChronoField.INSTANT_SECONDS;
66 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
67 import static java.time.temporal.ChronoUnit.DAYS;
68
69 import java.io.DataInput;
70 import java.io.DataOutput;
71 import java.io.IOException;
72 import java.io.InvalidObjectException;
73 import java.io.ObjectStreamException;
74 import java.io.Serializable;
75 import java.math.BigDecimal;
76 import java.math.BigInteger;
77 import java.math.RoundingMode;
78 import java.time.format.DateTimeParseException;
79 import java.time.temporal.ChronoField;
80 import java.time.temporal.ChronoUnit;
81 import java.time.temporal.Temporal;
82 import java.time.temporal.TemporalAccessor;
83 import java.time.temporal.TemporalAdder;
84 import java.time.temporal.TemporalSubtractor;
85 import java.time.temporal.TemporalUnit;
86 import java.util.Objects;
87
88 /**
89 * A duration between two instants on the time-line.
90 * <p>
91 * This class models a duration of time and is not tied to any instant.
92 * The model is of a directed duration, meaning that the duration may be negative.
93 * <p>
94 * A physical duration could be of infinite length.
95 * For practicality, the duration is stored with constraints similar to {@link Instant}.
96 * The duration uses nanosecond resolution with a maximum value of the seconds that can
97 * be held in a {@code long}. This is greater than the current estimated age of the universe.
98 * <p>
99 * The range of a duration requires the storage of a number larger than a {@code long}.
100 * To achieve this, the class stores a {@code long} representing seconds and an {@code int}
101 * representing nanosecond-of-second, which will always be between 0 and 999,999,999.
102 * <p>
103 * The duration is measured in "seconds", but these are not necessarily identical to
104 * the scientific "SI second" definition based on atomic clocks.
105 * This difference only impacts durations measured near a leap-second and should not affect
106 * most applications.
107 * See {@link Instant} for a discussion as to the meaning of the second and time-scales.
108 *
109 * <h3>Specification for implementors</h3>
110 * This class is immutable and thread-safe.
111 *
112 * @since 1.8
113 */
114 public final class Duration
115 implements TemporalAdder, TemporalSubtractor, Comparable<Duration>, Serializable {
116
117 /**
118 * Constant for a duration of zero.
119 */
120 public static final Duration ZERO = new Duration(0, 0);
121 /**
122 * Serialization version.
123 */
124 private static final long serialVersionUID = 3078945930695997490L;
125 /**
126 * Constant for nanos per second.
127 */
128 private static final int NANOS_PER_SECOND = 1000_000_000;
129 /**
130 * Constant for nanos per second.
131 */
132 private static final BigInteger BI_NANOS_PER_SECOND = BigInteger.valueOf(NANOS_PER_SECOND);
133
134 /**
135 * The number of seconds in the duration.
136 */
137 private final long seconds;
138 /**
139 * The number of nanoseconds in the duration, expressed as a fraction of the
140 * number of seconds. This is always positive, and never exceeds 999,999,999.
141 */
142 private final int nanos;
143
144 //-----------------------------------------------------------------------
145 /**
146 * Obtains an instance of {@code Duration} from a number of seconds.
147 * <p>
148 * The nanosecond in second field is set to zero.
149 *
150 * @param seconds the number of seconds, positive or negative
151 * @return a {@code Duration}, not null
152 */
153 public static Duration ofSeconds(long seconds) {
154 return create(seconds, 0);
155 }
156
157 /**
158 * Obtains an instance of {@code Duration} from a number of seconds
159 * and an adjustment in nanoseconds.
160 * <p>
161 * This method allows an arbitrary number of nanoseconds to be passed in.
162 * The factory will alter the values of the second and nanosecond in order
163 * to ensure that the stored nanosecond is in the range 0 to 999,999,999.
164 * For example, the following will result in the exactly the same duration:
165 * <pre>
166 * Duration.ofSeconds(3, 1);
167 * Duration.ofSeconds(4, -999_999_999);
168 * Duration.ofSeconds(2, 1000_000_001);
169 * </pre>
170 *
171 * @param seconds the number of seconds, positive or negative
172 * @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative
173 * @return a {@code Duration}, not null
174 * @throws ArithmeticException if the adjustment causes the seconds to exceed the capacity of {@code Duration}
175 */
176 public static Duration ofSeconds(long seconds, long nanoAdjustment) {
177 long secs = Math.addExact(seconds, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
178 int nos = (int)Math.floorMod(nanoAdjustment, NANOS_PER_SECOND);
179 return create(secs, nos);
180 }
181
182 //-----------------------------------------------------------------------
183 /**
184 * Obtains an instance of {@code Duration} from a number of milliseconds.
185 * <p>
186 * The seconds and nanoseconds are extracted from the specified milliseconds.
187 *
188 * @param millis the number of milliseconds, positive or negative
189 * @return a {@code Duration}, not null
190 */
191 public static Duration ofMillis(long millis) {
192 long secs = millis / 1000;
193 int mos = (int) (millis % 1000);
194 if (mos < 0) {
195 mos += 1000;
196 secs--;
197 }
198 return create(secs, mos * 1000_000);
199 }
200
201 //-----------------------------------------------------------------------
202 /**
203 * Obtains an instance of {@code Duration} from a number of nanoseconds.
204 * <p>
205 * The seconds and nanoseconds are extracted from the specified nanoseconds.
206 *
207 * @param nanos the number of nanoseconds, positive or negative
208 * @return a {@code Duration}, not null
209 */
210 public static Duration ofNanos(long nanos) {
211 long secs = nanos / NANOS_PER_SECOND;
212 int nos = (int) (nanos % NANOS_PER_SECOND);
213 if (nos < 0) {
214 nos += NANOS_PER_SECOND;
215 secs--;
216 }
217 return create(secs, nos);
218 }
219
220 //-----------------------------------------------------------------------
221 /**
222 * Obtains an instance of {@code Duration} from a number of standard length minutes.
223 * <p>
224 * The seconds are calculated based on the standard definition of a minute,
225 * where each minute is 60 seconds.
226 * The nanosecond in second field is set to zero.
227 *
228 * @param minutes the number of minutes, positive or negative
229 * @return a {@code Duration}, not null
230 * @throws ArithmeticException if the input minutes exceeds the capacity of {@code Duration}
231 */
232 public static Duration ofMinutes(long minutes) {
233 return create(Math.multiplyExact(minutes, 60), 0);
234 }
235
236 /**
237 * Obtains an instance of {@code Duration} from a number of standard length hours.
238 * <p>
239 * The seconds are calculated based on the standard definition of an hour,
240 * where each hour is 3600 seconds.
241 * The nanosecond in second field is set to zero.
242 *
243 * @param hours the number of hours, positive or negative
244 * @return a {@code Duration}, not null
245 * @throws ArithmeticException if the input hours exceeds the capacity of {@code Duration}
246 */
247 public static Duration ofHours(long hours) {
248 return create(Math.multiplyExact(hours, 3600), 0);
249 }
250
251 /**
252 * Obtains an instance of {@code Duration} from a number of standard 24 hour days.
253 * <p>
254 * The seconds are calculated based on the standard definition of a day,
255 * where each day is 86400 seconds which implies a 24 hour day.
256 * The nanosecond in second field is set to zero.
257 *
258 * @param days the number of days, positive or negative
259 * @return a {@code Duration}, not null
260 * @throws ArithmeticException if the input days exceeds the capacity of {@code Duration}
261 */
262 public static Duration ofDays(long days) {
263 return create(Math.multiplyExact(days, 86400), 0);
264 }
265
266 //-----------------------------------------------------------------------
267 /**
268 * Obtains an instance of {@code Duration} from a duration in the specified unit.
269 * <p>
270 * The parameters represent the two parts of a phrase like '6 Hours'. For example:
271 * <pre>
272 * Duration.of(3, SECONDS);
273 * Duration.of(465, HOURS);
274 * </pre>
275 * Only a subset of units are accepted by this method.
276 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or
277 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
278 *
279 * @param amount the amount of the duration, measured in terms of the unit, positive or negative
280 * @param unit the unit that the duration is measured in, must have an exact duration, not null
281 * @return a {@code Duration}, not null
282 * @throws DateTimeException if the period unit has an estimated duration
283 * @throws ArithmeticException if a numeric overflow occurs
284 */
285 public static Duration of(long amount, TemporalUnit unit) {
286 return ZERO.plus(amount, unit);
287 }
288
289 //-----------------------------------------------------------------------
290 /**
291 * Obtains an instance of {@code Duration} representing the duration between two instants.
292 * <p>
293 * A {@code Duration} represents a directed distance between two points on the time-line.
294 * As such, this method will return a negative duration if the end is before the start.
295 * To guarantee to obtain a positive duration call {@link #abs()} on the result of this factory.
296 *
297 * @param startInclusive the start instant, inclusive, not null
298 * @param endExclusive the end instant, exclusive, not null
299 * @return a {@code Duration}, not null
300 * @throws ArithmeticException if the calculation exceeds the capacity of {@code Duration}
301 */
302 public static Duration between(TemporalAccessor startInclusive, TemporalAccessor endExclusive) {
303 long secs = Math.subtractExact(endExclusive.getLong(INSTANT_SECONDS), startInclusive.getLong(INSTANT_SECONDS));
304 long nanos = endExclusive.getLong(NANO_OF_SECOND) - startInclusive.getLong(NANO_OF_SECOND);
305 secs = Math.addExact(secs, Math.floorDiv(nanos, NANOS_PER_SECOND));
306 nanos = Math.floorMod(nanos, NANOS_PER_SECOND);
307 return create(secs, (int) nanos); // safe from overflow
308 }
309
310 //-----------------------------------------------------------------------
311 /**
312 * Obtains an instance of {@code Duration} by parsing a text string.
313 * <p>
314 * This will parse the string produced by {@link #toString()} which is
315 * the ISO-8601 format {@code PTnS} where {@code n} is
316 * the number of seconds with optional decimal part.
317 * The number must consist of ASCII numerals.
318 * There must only be a negative sign at the start of the number and it can
319 * only be present if the value is less than zero.
320 * There must be at least one digit before any decimal point.
321 * There must be between 1 and 9 inclusive digits after any decimal point.
322 * The letters (P, T and S) will be accepted in upper or lower case.
323 * The decimal point may be either a dot or a comma.
324 *
325 * @param text the text to parse, not null
326 * @return a {@code Duration}, not null
327 * @throws DateTimeParseException if the text cannot be parsed to a {@code Duration}
328 */
329 public static Duration parse(final CharSequence text) {
330 Objects.requireNonNull(text, "text");
331 int len = text.length();
332 if (len < 4 ||
333 (text.charAt(0) != 'P' && text.charAt(0) != 'p') ||
334 (text.charAt(1) != 'T' && text.charAt(1) != 't') ||
335 (text.charAt(len - 1) != 'S' && text.charAt(len - 1) != 's') ||
336 (len == 5 && text.charAt(2) == '-' && text.charAt(3) == '0')) {
337 throw new DateTimeParseException("Duration could not be parsed: " + text, text, 0);
338 }
339 String numberText = text.subSequence(2, len - 1).toString().replace(',', '.');
340 if (numberText.charAt(0) == '+') {
341 throw new DateTimeParseException("Duration could not be parsed: " + text, text, 2);
342 }
343 int dot = numberText.indexOf('.');
344 try {
345 if (dot == -1) {
346 // no decimal places
347 if (numberText.startsWith("-0")) {
348 throw new DateTimeParseException("Duration could not be parsed: " + text, text, 2);
349 }
350 return create(Long.parseLong(numberText), 0);
351 }
352 // decimal places
353 boolean negative = false;
354 if (numberText.charAt(0) == '-') {
355 negative = true;
356 }
357 long secs = Long.parseLong(numberText.substring(0, dot));
358 numberText = numberText.substring(dot + 1);
359 len = numberText.length();
360 if (len == 0 || len > 9 || numberText.charAt(0) == '-' || numberText.charAt(0) == '+') {
361 throw new DateTimeParseException("Duration could not be parsed: " + text, text, 2);
362 }
363 int nanos = Integer.parseInt(numberText);
364 switch (len) {
365 case 1:
366 nanos *= 100000000;
367 break;
368 case 2:
369 nanos *= 10000000;
370 break;
371 case 3:
372 nanos *= 1000000;
373 break;
374 case 4:
375 nanos *= 100000;
376 break;
377 case 5:
378 nanos *= 10000;
379 break;
380 case 6:
381 nanos *= 1000;
382 break;
383 case 7:
384 nanos *= 100;
385 break;
386 case 8:
387 nanos *= 10;
388 break;
389 }
390 return negative ? ofSeconds(secs, -nanos) : create(secs, nanos);
391
392 } catch (ArithmeticException | NumberFormatException ex) {
393 throw new DateTimeParseException("Duration could not be parsed: " + text, text, 2, ex);
394 }
395 }
396
397 //-----------------------------------------------------------------------
398 /**
399 * Obtains an instance of {@code Duration} using seconds and nanoseconds.
400 *
401 * @param seconds the length of the duration in seconds, positive or negative
402 * @param nanoAdjustment the nanosecond adjustment within the second, from 0 to 999,999,999
403 */
404 private static Duration create(long seconds, int nanoAdjustment) {
405 if ((seconds | nanoAdjustment) == 0) {
406 return ZERO;
407 }
408 return new Duration(seconds, nanoAdjustment);
409 }
410
411 /**
412 * Constructs an instance of {@code Duration} using seconds and nanoseconds.
413 *
414 * @param seconds the length of the duration in seconds, positive or negative
415 * @param nanos the nanoseconds within the second, from 0 to 999,999,999
416 */
417 private Duration(long seconds, int nanos) {
418 super();
419 this.seconds = seconds;
420 this.nanos = nanos;
421 }
422
423 //-----------------------------------------------------------------------
424 /**
425 * Checks if this duration is zero length.
426 * <p>
427 * A {@code Duration} represents a directed distance between two points on
428 * the time-line and can therefore be positive, zero or negative.
429 * This method checks whether the length is zero.
430 *
431 * @return true if this duration has a total length equal to zero
432 */
433 public boolean isZero() {
434 return (seconds | nanos) == 0;
435 }
436
437 /**
438 * Checks if this duration is positive, excluding zero.
439 * <p>
440 * A {@code Duration} represents a directed distance between two points on
441 * the time-line and can therefore be positive, zero or negative.
442 * This method checks whether the length is greater than zero.
443 *
444 * @return true if this duration has a total length greater than zero
445 */
446 public boolean isPositive() {
447 return seconds >= 0 && ((seconds | nanos) != 0);
448 }
449
450 /**
451 * Checks if this duration is negative, excluding zero.
452 * <p>
453 * A {@code Duration} represents a directed distance between two points on
454 * the time-line and can therefore be positive, zero or negative.
455 * This method checks whether the length is less than zero.
456 *
457 * @return true if this duration has a total length less than zero
458 */
459 public boolean isNegative() {
460 return seconds < 0;
461 }
462
463 //-----------------------------------------------------------------------
464 /**
465 * Gets the number of seconds in this duration.
466 * <p>
467 * The length of the duration is stored using two fields - seconds and nanoseconds.
482 /**
483 * Gets the number of nanoseconds within the second in this duration.
484 * <p>
485 * The length of the duration is stored using two fields - seconds and nanoseconds.
486 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to
487 * the length in seconds.
488 * The total duration is defined by calling this method and {@link #getSeconds()}.
489 * <p>
490 * A {@code Duration} represents a directed distance between two points on the time-line.
491 * A negative duration is expressed by the negative sign of the seconds part.
492 * A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds.
493 *
494 * @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999
495 */
496 public int getNano() {
497 return nanos;
498 }
499
500 //-----------------------------------------------------------------------
501 /**
502 * Returns a copy of this duration with the specified duration added.
503 * <p>
504 * This instance is immutable and unaffected by this method call.
505 *
506 * @param duration the duration to add, positive or negative, not null
507 * @return a {@code Duration} based on this duration with the specified duration added, not null
508 * @throws ArithmeticException if numeric overflow occurs
509 */
510 public Duration plus(Duration duration) {
511 return plus(duration.getSeconds(), duration.getNano());
512 }
513
514 /**
515 * Returns a copy of this duration with the specified duration added.
516 * <p>
517 * The duration amount is measured in terms of the specified unit.
518 * Only a subset of units are accepted by this method.
519 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or
520 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
521 * <p>
535 throw new DateTimeException("Unit must not have an estimated duration");
536 }
537 if (amountToAdd == 0) {
538 return this;
539 }
540 if (unit instanceof ChronoUnit) {
541 switch ((ChronoUnit) unit) {
542 case NANOS: return plusNanos(amountToAdd);
543 case MICROS: return plusSeconds((amountToAdd / (1000_000L * 1000)) * 1000).plusNanos((amountToAdd % (1000_000L * 1000)) * 1000);
544 case MILLIS: return plusMillis(amountToAdd);
545 case SECONDS: return plusSeconds(amountToAdd);
546 }
547 return plusSeconds(Math.multiplyExact(unit.getDuration().seconds, amountToAdd));
548 }
549 Duration duration = unit.getDuration().multipliedBy(amountToAdd);
550 return plusSeconds(duration.getSeconds()).plusNanos(duration.getNano());
551 }
552
553 //-----------------------------------------------------------------------
554 /**
555 * Returns a copy of this duration with the specified duration in seconds added.
556 * <p>
557 * This instance is immutable and unaffected by this method call.
558 *
559 * @param secondsToAdd the seconds to add, positive or negative
560 * @return a {@code Duration} based on this duration with the specified seconds added, not null
561 * @throws ArithmeticException if numeric overflow occurs
562 */
563 public Duration plusSeconds(long secondsToAdd) {
564 return plus(secondsToAdd, 0);
565 }
566
567 /**
568 * Returns a copy of this duration with the specified duration in milliseconds added.
569 * <p>
570 * This instance is immutable and unaffected by this method call.
571 *
572 * @param millisToAdd the milliseconds to add, positive or negative
573 * @return a {@code Duration} based on this duration with the specified milliseconds added, not null
574 * @throws ArithmeticException if numeric overflow occurs
634 * Returns a copy of this duration with the specified duration subtracted.
635 * <p>
636 * The duration amount is measured in terms of the specified unit.
637 * Only a subset of units are accepted by this method.
638 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or
639 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
640 * <p>
641 * This instance is immutable and unaffected by this method call.
642 *
643 * @param amountToSubtract the amount of the period, measured in terms of the unit, positive or negative
644 * @param unit the unit that the period is measured in, must have an exact duration, not null
645 * @return a {@code Duration} based on this duration with the specified duration subtracted, not null
646 * @throws ArithmeticException if numeric overflow occurs
647 */
648 public Duration minus(long amountToSubtract, TemporalUnit unit) {
649 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
650 }
651
652 //-----------------------------------------------------------------------
653 /**
654 * Returns a copy of this duration with the specified duration in seconds subtracted.
655 * <p>
656 * This instance is immutable and unaffected by this method call.
657 *
658 * @param secondsToSubtract the seconds to subtract, positive or negative
659 * @return a {@code Duration} based on this duration with the specified seconds subtracted, not null
660 * @throws ArithmeticException if numeric overflow occurs
661 */
662 public Duration minusSeconds(long secondsToSubtract) {
663 return (secondsToSubtract == Long.MIN_VALUE ? plusSeconds(Long.MAX_VALUE).plusSeconds(1) : plusSeconds(-secondsToSubtract));
664 }
665
666 /**
667 * Returns a copy of this duration with the specified duration in milliseconds subtracted.
668 * <p>
669 * This instance is immutable and unaffected by this method call.
670 *
671 * @param millisToSubtract the milliseconds to subtract, positive or negative
672 * @return a {@code Duration} based on this duration with the specified milliseconds subtracted, not null
673 * @throws ArithmeticException if numeric overflow occurs
699 * @return a {@code Duration} based on this duration multiplied by the specified scalar, not null
700 * @throws ArithmeticException if numeric overflow occurs
701 */
702 public Duration multipliedBy(long multiplicand) {
703 if (multiplicand == 0) {
704 return ZERO;
705 }
706 if (multiplicand == 1) {
707 return this;
708 }
709 return create(toSeconds().multiply(BigDecimal.valueOf(multiplicand)));
710 }
711
712 /**
713 * Returns a copy of this duration divided by the specified value.
714 * <p>
715 * This instance is immutable and unaffected by this method call.
716 *
717 * @param divisor the value to divide the duration by, positive or negative, not zero
718 * @return a {@code Duration} based on this duration divided by the specified divisor, not null
719 * @throws ArithmeticException if the divisor is zero
720 * @throws ArithmeticException if numeric overflow occurs
721 */
722 public Duration dividedBy(long divisor) {
723 if (divisor == 0) {
724 throw new ArithmeticException("Cannot divide by zero");
725 }
726 if (divisor == 1) {
727 return this;
728 }
729 return create(toSeconds().divide(BigDecimal.valueOf(divisor), RoundingMode.DOWN));
730 }
731
732 /**
733 * Converts this duration to the total length in seconds and
734 * fractional nanoseconds expressed as a {@code BigDecimal}.
735 *
736 * @return the total length of the duration in seconds, with a scale of 9, not null
737 */
738 private BigDecimal toSeconds() {
739 return BigDecimal.valueOf(seconds).add(BigDecimal.valueOf(nanos, 9));
740 }
777 * This method returns a positive duration by effectively removing the sign from any negative total length.
778 * For example, {@code PT-1.3S} will be returned as {@code PT1.3S}.
779 * <p>
780 * This instance is immutable and unaffected by this method call.
781 *
782 * @return a {@code Duration} based on this duration with an absolute length, not null
783 * @throws ArithmeticException if numeric overflow occurs
784 */
785 public Duration abs() {
786 return isNegative() ? negated() : this;
787 }
788
789 //-------------------------------------------------------------------------
790 /**
791 * Adds this duration to the specified temporal object.
792 * <p>
793 * This returns a temporal object of the same observable type as the input
794 * with this duration added.
795 * <p>
796 * In most cases, it is clearer to reverse the calling pattern by using
797 * {@link Temporal#plus(TemporalAdder)}.
798 * <pre>
799 * // these two lines are equivalent, but the second approach is recommended
800 * dateTime = thisDuration.addTo(dateTime);
801 * dateTime = dateTime.plus(thisDuration);
802 * </pre>
803 * <p>
804 * A {@code Duration} can only be added to a {@code Temporal} that
805 * represents an instant and can supply {@link ChronoField#INSTANT_SECONDS}.
806 * <p>
807 * This instance is immutable and unaffected by this method call.
808 *
809 * @param temporal the temporal object to adjust, not null
810 * @return an object of the same type with the adjustment made, not null
811 * @throws DateTimeException if unable to add
812 * @throws ArithmeticException if numeric overflow occurs
813 */
814 @Override
815 public Temporal addTo(Temporal temporal) {
816 long instantSecs = temporal.getLong(INSTANT_SECONDS);
817 long instantNanos = temporal.getLong(NANO_OF_SECOND);
818 instantSecs = Math.addExact(instantSecs, seconds);
819 instantNanos = Math.addExact(instantNanos, nanos);
820 instantSecs = Math.addExact(instantSecs, Math.floorDiv(instantNanos, NANOS_PER_SECOND));
821 instantNanos = Math.floorMod(instantNanos, NANOS_PER_SECOND);
822 return temporal.with(INSTANT_SECONDS, instantSecs).with(NANO_OF_SECOND, instantNanos);
823 }
824
825 /**
826 * Subtracts this duration from the specified temporal object.
827 * <p>
828 * This returns a temporal object of the same observable type as the input
829 * with this duration subtracted.
830 * <p>
831 * In most cases, it is clearer to reverse the calling pattern by using
832 * {@link Temporal#minus(TemporalSubtractor)}.
833 * <pre>
834 * // these two lines are equivalent, but the second approach is recommended
835 * dateTime = thisDuration.subtractFrom(dateTime);
836 * dateTime = dateTime.minus(thisDuration);
837 * </pre>
838 * <p>
839 * A {@code Duration} can only be subtracted from a {@code Temporal} that
840 * represents an instant and can supply {@link ChronoField#INSTANT_SECONDS}.
841 * <p>
842 * This instance is immutable and unaffected by this method call.
843 *
844 * @param temporal the temporal object to adjust, not null
845 * @return an object of the same type with the adjustment made, not null
846 * @throws DateTimeException if unable to subtract
847 * @throws ArithmeticException if numeric overflow occurs
848 */
849 @Override
850 public Temporal subtractFrom(Temporal temporal) {
851 long instantSecs = temporal.getLong(INSTANT_SECONDS);
852 long instantNanos = temporal.getLong(NANO_OF_SECOND);
853 instantSecs = Math.subtractExact(instantSecs, seconds);
854 instantNanos = Math.subtractExact(instantNanos, nanos);
855 instantSecs = Math.addExact(instantSecs, Math.floorDiv(instantNanos, NANOS_PER_SECOND));
856 instantNanos = Math.floorMod(instantNanos, NANOS_PER_SECOND);
857 return temporal.with(INSTANT_SECONDS, instantSecs).with(NANO_OF_SECOND, instantNanos);
858 }
859
860 //-----------------------------------------------------------------------
861 /**
862 * Converts this duration to the total length in milliseconds.
863 * <p>
864 * If this duration is too large to fit in a {@code long} milliseconds, then an
865 * exception is thrown.
866 * <p>
867 * If this duration has greater than millisecond precision, then the conversion
868 * will drop any excess precision information as though the amount in nanoseconds
869 * was subject to integer division by one million.
870 *
871 * @return the total length of the duration in milliseconds
872 * @throws ArithmeticException if numeric overflow occurs
873 */
874 public long toMillis() {
875 long millis = Math.multiplyExact(seconds, 1000);
876 millis = Math.addExact(millis, nanos / 1000_000);
877 return millis;
878 }
879
880 /**
881 * Converts this duration to the total length in nanoseconds expressed as a {@code long}.
882 * <p>
883 * If this duration is too large to fit in a {@code long} nanoseconds, then an
884 * exception is thrown.
885 *
886 * @return the total length of the duration in nanoseconds
887 * @throws ArithmeticException if numeric overflow occurs
888 */
889 public long toNanos() {
890 long millis = Math.multiplyExact(seconds, 1000_000_000);
891 millis = Math.addExact(millis, nanos);
892 return millis;
893 }
894
895 //-----------------------------------------------------------------------
896 /**
897 * Compares this duration to the specified {@code Duration}.
898 * <p>
899 * The comparison is based on the total length of the durations.
900 * It is "consistent with equals", as defined by {@link Comparable}.
901 *
902 * @param otherDuration the other duration to compare to, not null
903 * @return the comparator value, negative if less, positive if greater
904 */
905 @Override
906 public int compareTo(Duration otherDuration) {
907 int cmp = Long.compare(seconds, otherDuration.seconds);
908 if (cmp != 0) {
909 return cmp;
910 }
911 return nanos - otherDuration.nanos;
912 }
913
914 /**
915 * Checks if this duration is greater than the specified {@code Duration}.
916 * <p>
917 * The comparison is based on the total length of the durations.
918 *
919 * @param otherDuration the other duration to compare to, not null
920 * @return true if this duration is greater than the specified duration
921 */
922 public boolean isGreaterThan(Duration otherDuration) {
923 return compareTo(otherDuration) > 0;
924 }
925
926 /**
927 * Checks if this duration is less than the specified {@code Duration}.
928 * <p>
929 * The comparison is based on the total length of the durations.
930 *
931 * @param otherDuration the other duration to compare to, not null
932 * @return true if this duration is less than the specified duration
933 */
934 public boolean isLessThan(Duration otherDuration) {
935 return compareTo(otherDuration) < 0;
936 }
937
938 //-----------------------------------------------------------------------
939 /**
940 * Checks if this duration is equal to the specified {@code Duration}.
941 * <p>
942 * The comparison is based on the total length of the durations.
943 *
944 * @param otherDuration the other duration, null returns false
945 * @return true if the other duration is equal to this one
946 */
947 @Override
948 public boolean equals(Object otherDuration) {
949 if (this == otherDuration) {
950 return true;
951 }
952 if (otherDuration instanceof Duration) {
953 Duration other = (Duration) otherDuration;
954 return this.seconds == other.seconds &&
955 this.nanos == other.nanos;
956 }
957 return false;
958 }
959
960 /**
961 * A hash code for this duration.
962 *
963 * @return a suitable hash code
964 */
965 @Override
966 public int hashCode() {
967 return ((int) (seconds ^ (seconds >>> 32))) + (51 * nanos);
968 }
969
970 //-----------------------------------------------------------------------
971 /**
972 * A string representation of this duration using ISO-8601 seconds
973 * based representation, such as {@code PT12.345S}.
974 * <p>
975 * The format of the returned string will be {@code PTnS} where n is
976 * the seconds and fractional seconds of the duration.
977 *
978 * @return an ISO-8601 representation of this duration, not null
979 */
980 @Override
981 public String toString() {
982 StringBuilder buf = new StringBuilder(24);
983 buf.append("PT");
984 if (seconds < 0 && nanos > 0) {
985 if (seconds == -1) {
986 buf.append("-0");
987 } else {
988 buf.append(seconds + 1);
989 }
990 } else {
991 buf.append(seconds);
992 }
993 if (nanos > 0) {
994 int pos = buf.length();
995 if (seconds < 0) {
996 buf.append(2 * NANOS_PER_SECOND - nanos);
997 } else {
998 buf.append(nanos + NANOS_PER_SECOND);
999 }
1000 while (buf.charAt(buf.length() - 1) == '0') {
1001 buf.setLength(buf.length() - 1);
1002 }
1003 buf.setCharAt(pos, '.');
1004 }
1005 buf.append('S');
1006 return buf.toString();
1007 }
1008
1009 //-----------------------------------------------------------------------
1010 /**
1011 * Writes the object using a
1012 * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1013 * <pre>
1014 * out.writeByte(1); // identifies this as a Duration
1015 * out.writeLong(seconds);
|
44 * and/or other materials provided with the distribution.
45 *
46 * * Neither the name of JSR-310 nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
51 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
52 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
53 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
54 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
55 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
56 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
57 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
58 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
59 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
60 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61 */
62 package java.time;
63
64 import static java.time.LocalTime.NANOS_PER_SECOND;
65 import static java.time.LocalTime.SECONDS_PER_DAY;
66 import static java.time.LocalTime.SECONDS_PER_HOUR;
67 import static java.time.LocalTime.SECONDS_PER_MINUTE;
68 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
69 import static java.time.temporal.ChronoUnit.DAYS;
70 import static java.time.temporal.ChronoUnit.NANOS;
71 import static java.time.temporal.ChronoUnit.SECONDS;
72
73 import java.io.DataInput;
74 import java.io.DataOutput;
75 import java.io.IOException;
76 import java.io.InvalidObjectException;
77 import java.io.ObjectStreamException;
78 import java.io.Serializable;
79 import java.math.BigDecimal;
80 import java.math.BigInteger;
81 import java.math.RoundingMode;
82 import java.time.format.DateTimeParseException;
83 import java.time.temporal.ChronoField;
84 import java.time.temporal.ChronoUnit;
85 import java.time.temporal.Temporal;
86 import java.time.temporal.TemporalAmount;
87 import java.time.temporal.TemporalUnit;
88 import java.util.Arrays;
89 import java.util.Collections;
90 import java.util.List;
91 import java.util.Objects;
92 import java.util.regex.Matcher;
93 import java.util.regex.Pattern;
94
95 /**
96 * A time-based amount of time, such as '34.5 seconds'.
97 * <p>
98 * This class models a quantity or amount of time in terms of seconds and nanoseconds.
99 * It can be accessed using other duration-based units, such as minutes and hours.
100 * In addition, the {@link ChronoUnit#DAYS DAYS} unit can be used and is treated as
101 * exactly equal to 24 hours, thus ignoring daylight savings effects.
102 * See {@link Period} for the date-based equivalent to this class.
103 * <p>
104 * A physical duration could be of infinite length.
105 * For practicality, the duration is stored with constraints similar to {@link Instant}.
106 * The duration uses nanosecond resolution with a maximum value of the seconds that can
107 * be held in a {@code long}. This is greater than the current estimated age of the universe.
108 * <p>
109 * The range of a duration requires the storage of a number larger than a {@code long}.
110 * To achieve this, the class stores a {@code long} representing seconds and an {@code int}
111 * representing nanosecond-of-second, which will always be between 0 and 999,999,999.
112 * The model is of a directed duration, meaning that the duration may be negative.
113 * <p>
114 * The duration is measured in "seconds", but these are not necessarily identical to
115 * the scientific "SI second" definition based on atomic clocks.
116 * This difference only impacts durations measured near a leap-second and should not affect
117 * most applications.
118 * See {@link Instant} for a discussion as to the meaning of the second and time-scales.
119 *
120 * <h3>Specification for implementors</h3>
121 * This class is immutable and thread-safe.
122 *
123 * @since 1.8
124 */
125 public final class Duration
126 implements TemporalAmount, Comparable<Duration>, Serializable {
127
128 /**
129 * Constant for a duration of zero.
130 */
131 public static final Duration ZERO = new Duration(0, 0);
132 /**
133 * Serialization version.
134 */
135 private static final long serialVersionUID = 3078945930695997490L;
136 /**
137 * Constant for nanos per second.
138 */
139 private static final BigInteger BI_NANOS_PER_SECOND = BigInteger.valueOf(NANOS_PER_SECOND);
140 /**
141 * The pattern for parsing.
142 */
143 private final static Pattern PATTERN =
144 Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)D)?" +
145 "(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]{0,9}))?S)?)?",
146 Pattern.CASE_INSENSITIVE);
147
148 /**
149 * The number of seconds in the duration.
150 */
151 private final long seconds;
152 /**
153 * The number of nanoseconds in the duration, expressed as a fraction of the
154 * number of seconds. This is always positive, and never exceeds 999,999,999.
155 */
156 private final int nanos;
157
158 //-----------------------------------------------------------------------
159 /**
160 * Obtains a {@code Duration} representing a number of standard 24 hour days.
161 * <p>
162 * The seconds are calculated based on the standard definition of a day,
163 * where each day is 86400 seconds which implies a 24 hour day.
164 * The nanosecond in second field is set to zero.
165 *
166 * @param days the number of days, positive or negative
167 * @return a {@code Duration}, not null
168 * @throws ArithmeticException if the input days exceeds the capacity of {@code Duration}
169 */
170 public static Duration ofDays(long days) {
171 return create(Math.multiplyExact(days, SECONDS_PER_DAY), 0);
172 }
173
174 /**
175 * Obtains a {@code Duration} representing a number of standard hours.
176 * <p>
177 * The seconds are calculated based on the standard definition of an hour,
178 * where each hour is 3600 seconds.
179 * The nanosecond in second field is set to zero.
180 *
181 * @param hours the number of hours, positive or negative
182 * @return a {@code Duration}, not null
183 * @throws ArithmeticException if the input hours exceeds the capacity of {@code Duration}
184 */
185 public static Duration ofHours(long hours) {
186 return create(Math.multiplyExact(hours, SECONDS_PER_HOUR), 0);
187 }
188
189 /**
190 * Obtains a {@code Duration} representing a number of standard minutes.
191 * <p>
192 * The seconds are calculated based on the standard definition of a minute,
193 * where each minute is 60 seconds.
194 * The nanosecond in second field is set to zero.
195 *
196 * @param minutes the number of minutes, positive or negative
197 * @return a {@code Duration}, not null
198 * @throws ArithmeticException if the input minutes exceeds the capacity of {@code Duration}
199 */
200 public static Duration ofMinutes(long minutes) {
201 return create(Math.multiplyExact(minutes, SECONDS_PER_MINUTE), 0);
202 }
203
204 //-----------------------------------------------------------------------
205 /**
206 * Obtains a {@code Duration} representing a number of seconds.
207 * <p>
208 * The nanosecond in second field is set to zero.
209 *
210 * @param seconds the number of seconds, positive or negative
211 * @return a {@code Duration}, not null
212 */
213 public static Duration ofSeconds(long seconds) {
214 return create(seconds, 0);
215 }
216
217 /**
218 * Obtains a {@code Duration} representing a number of seconds and an
219 * adjustment in nanoseconds.
220 * <p>
221 * This method allows an arbitrary number of nanoseconds to be passed in.
222 * The factory will alter the values of the second and nanosecond in order
223 * to ensure that the stored nanosecond is in the range 0 to 999,999,999.
224 * For example, the following will result in the exactly the same duration:
225 * <pre>
226 * Duration.ofSeconds(3, 1);
227 * Duration.ofSeconds(4, -999_999_999);
228 * Duration.ofSeconds(2, 1000_000_001);
229 * </pre>
230 *
231 * @param seconds the number of seconds, positive or negative
232 * @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative
233 * @return a {@code Duration}, not null
234 * @throws ArithmeticException if the adjustment causes the seconds to exceed the capacity of {@code Duration}
235 */
236 public static Duration ofSeconds(long seconds, long nanoAdjustment) {
237 long secs = Math.addExact(seconds, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
238 int nos = (int) Math.floorMod(nanoAdjustment, NANOS_PER_SECOND);
239 return create(secs, nos);
240 }
241
242 //-----------------------------------------------------------------------
243 /**
244 * Obtains a {@code Duration} representing a number of milliseconds.
245 * <p>
246 * The seconds and nanoseconds are extracted from the specified milliseconds.
247 *
248 * @param millis the number of milliseconds, positive or negative
249 * @return a {@code Duration}, not null
250 */
251 public static Duration ofMillis(long millis) {
252 long secs = millis / 1000;
253 int mos = (int) (millis % 1000);
254 if (mos < 0) {
255 mos += 1000;
256 secs--;
257 }
258 return create(secs, mos * 1000_000);
259 }
260
261 //-----------------------------------------------------------------------
262 /**
263 * Obtains a {@code Duration} representing a number of nanoseconds.
264 * <p>
265 * The seconds and nanoseconds are extracted from the specified nanoseconds.
266 *
267 * @param nanos the number of nanoseconds, positive or negative
268 * @return a {@code Duration}, not null
269 */
270 public static Duration ofNanos(long nanos) {
271 long secs = nanos / NANOS_PER_SECOND;
272 int nos = (int) (nanos % NANOS_PER_SECOND);
273 if (nos < 0) {
274 nos += NANOS_PER_SECOND;
275 secs--;
276 }
277 return create(secs, nos);
278 }
279
280 //-----------------------------------------------------------------------
281 /**
282 * Obtains a {@code Duration} representing an amount in the specified unit.
283 * <p>
284 * The parameters represent the two parts of a phrase like '6 Hours'. For example:
285 * <pre>
286 * Duration.of(3, SECONDS);
287 * Duration.of(465, HOURS);
288 * </pre>
289 * Only a subset of units are accepted by this method.
290 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or
291 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
292 *
293 * @param amount the amount of the duration, measured in terms of the unit, positive or negative
294 * @param unit the unit that the duration is measured in, must have an exact duration, not null
295 * @return a {@code Duration}, not null
296 * @throws DateTimeException if the period unit has an estimated duration
297 * @throws ArithmeticException if a numeric overflow occurs
298 */
299 public static Duration of(long amount, TemporalUnit unit) {
300 return ZERO.plus(amount, unit);
301 }
302
303 //-----------------------------------------------------------------------
304 /**
305 * Obtains a {@code Duration} representing the duration between two instants.
306 * <p>
307 * This calculates the duration between two temporal objects of the same type.
308 * The difference in seconds is calculated using
309 * {@link Temporal#periodUntil(Temporal, TemporalUnit)}.
310 * The difference in nanoseconds is calculated using by querying the
311 * {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} field.
312 * <p>
313 * The result of this method can be a negative period if the end is before the start.
314 * To guarantee to obtain a positive duration call {@link #abs()} on the result.
315 *
316 * @param startInclusive the start instant, inclusive, not null
317 * @param endExclusive the end instant, exclusive, not null
318 * @return a {@code Duration}, not null
319 * @throws ArithmeticException if the calculation exceeds the capacity of {@code Duration}
320 */
321 public static Duration between(Temporal startInclusive, Temporal endExclusive) {
322 long secs = startInclusive.periodUntil(endExclusive, SECONDS);
323 long nanos;
324 try {
325 nanos = endExclusive.getLong(NANO_OF_SECOND) - startInclusive.getLong(NANO_OF_SECOND);
326 } catch (DateTimeException ex) {
327 nanos = 0;
328 }
329 return ofSeconds(secs, nanos);
330 }
331
332 //-----------------------------------------------------------------------
333 /**
334 * Obtains a {@code Duration} from a text string such as {@code PnDTnHnMn.nS}.
335 * <p>
336 * This will parse a textual representation of a duration, including the
337 * string produced by {@code toString()}. The formats accepted are based
338 * on the ISO-8601 duration format {@code PnDTnHnMn.nS} with days
339 * considered to be exactly 24 hours.
340 * <p>
341 * The string starts with an optional sign, denoted by the ASCII negative
342 * or positive symbol. If negative, the whole period is negated.
343 * The ASCII letter "P" is next in upper or lower case.
344 * There are then four sections, each consisting of a number and a suffix.
345 * The sections have suffixes in ASCII of "D", "H", "M" and "S" for
346 * days, hours, minutes and seconds, accepted in upper or lower case.
347 * The suffixes must occur in order. The ASCII letter "T" must occur before
348 * the first occurrence, if any, of an hour, minute or second section.
349 * At least one of the four sections must be present, and if "T" is present
350 * there must be at least one section after the "T".
351 * The number part of each section must consist of one or more ASCII digits.
352 * The number may be prefixed by the ASCII negative or positive symbol.
353 * The number of days, hours and minutes must parse to an {@code long}.
354 * The number of seconds must parse to an {@code long} with optional fraction.
355 * The decimal point may be either a dot or a comma.
356 * The fractional part may have from zero to 9 digits.
357 * <p>
358 * The leading plus/minus sign, and negative values for other units are
359 * not part of the ISO-8601 standard.
360 * <p>
361 * Examples:
362 * <pre>
363 * "PT20.345S" -> parses as "20.345 seconds"
364 * "PT15M" -> parses as "15 minutes" (where a minute is 60 seconds)
365 * "PT10H" -> parses as "10 hours" (where an hour is 3600 seconds)
366 * "P2D" -> parses as "2 days" (where a day is 24 hours or 86400 seconds)
367 * "P2DT3H4M" -> parses as "2 days, 3 hours and 4 minutes"
368 * "P-6H3M" -> parses as "-6 hours and +3 minutes"
369 * "-P6H3M" -> parses as "-6 hours and -3 minutes"
370 * "-P-6H+3M" -> parses as "+6 hours and -3 minutes"
371 * </pre>
372 *
373 * @param text the text to parse, not null
374 * @return the parsed duration, not null
375 * @throws DateTimeParseException if the text cannot be parsed to a duration
376 */
377 public static Duration parse(CharSequence text) {
378 Objects.requireNonNull(text, "text");
379 Matcher matcher = PATTERN.matcher(text);
380 if (matcher.matches()) {
381 // check for letter T but no time sections
382 if ("T".equals(matcher.group(3)) == false) {
383 boolean negate = "-".equals(matcher.group(1));
384 String dayMatch = matcher.group(2);
385 String hourMatch = matcher.group(4);
386 String minuteMatch = matcher.group(5);
387 String secondMatch = matcher.group(6);
388 String fractionMatch = matcher.group(7);
389 if (dayMatch != null || hourMatch != null || minuteMatch != null || secondMatch != null) {
390 long daysAsSecs = parseNumber(text, dayMatch, SECONDS_PER_DAY, "days");
391 long hoursAsSecs = parseNumber(text, hourMatch, SECONDS_PER_HOUR, "hours");
392 long minsAsSecs = parseNumber(text, minuteMatch, SECONDS_PER_MINUTE, "minutes");
393 long seconds = parseNumber(text, secondMatch, 1, "seconds");
394 int nanos = parseFraction(text, fractionMatch, seconds < 0 ? -1 : 1);
395 try {
396 return create(negate, daysAsSecs, hoursAsSecs, minsAsSecs, seconds, nanos);
397 } catch (ArithmeticException ex) {
398 throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: overflow", text, 0).initCause(ex);
399 }
400 }
401 }
402 }
403 throw new DateTimeParseException("Text cannot be parsed to a Duration", text, 0);
404 }
405
406 private static long parseNumber(CharSequence text, String parsed, int multiplier, String errorText) {
407 // regex limits to [-+]?[0-9]+
408 if (parsed == null) {
409 return 0;
410 }
411 try {
412 long val = Long.parseLong(parsed);
413 return Math.multiplyExact(val, multiplier);
414 } catch (NumberFormatException | ArithmeticException ex) {
415 throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: " + errorText, text, 0).initCause(ex);
416 }
417 }
418
419 private static int parseFraction(CharSequence text, String parsed, int negate) {
420 // regex limits to [0-9]{0,9}
421 if (parsed == null || parsed.length() == 0) {
422 return 0;
423 }
424 try {
425 parsed = (parsed + "000000000").substring(0, 9);
426 return Integer.parseInt(parsed) * negate;
427 } catch (NumberFormatException | ArithmeticException ex) {
428 throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: fraction", text, 0).initCause(ex);
429 }
430 }
431
432 private static Duration create(boolean negate, long daysAsSecs, long hoursAsSecs, long minsAsSecs, long secs, int nanos) {
433 long seconds = Math.addExact(daysAsSecs, Math.addExact(hoursAsSecs, Math.addExact(minsAsSecs, secs)));
434 if (negate) {
435 return ofSeconds(seconds, nanos).negated();
436 }
437 return ofSeconds(seconds, nanos);
438 }
439
440 //-----------------------------------------------------------------------
441 /**
442 * Obtains an instance of {@code Duration} using seconds and nanoseconds.
443 *
444 * @param seconds the length of the duration in seconds, positive or negative
445 * @param nanoAdjustment the nanosecond adjustment within the second, from 0 to 999,999,999
446 */
447 private static Duration create(long seconds, int nanoAdjustment) {
448 if ((seconds | nanoAdjustment) == 0) {
449 return ZERO;
450 }
451 return new Duration(seconds, nanoAdjustment);
452 }
453
454 /**
455 * Constructs an instance of {@code Duration} using seconds and nanoseconds.
456 *
457 * @param seconds the length of the duration in seconds, positive or negative
458 * @param nanos the nanoseconds within the second, from 0 to 999,999,999
459 */
460 private Duration(long seconds, int nanos) {
461 super();
462 this.seconds = seconds;
463 this.nanos = nanos;
464 }
465
466 //-----------------------------------------------------------------------
467 /**
468 * Gets the value of the requested unit.
469 * <p>
470 * This returns a value for each of the two supported units,
471 * {@link ChronoUnit#SECONDS SECONDS} and {@link ChronoUnit#NANOS NANOS}.
472 * All other units throw an exception.
473 *
474 * @param unit the {@code TemporalUnit} for which to return the value
475 * @return the long value of the unit
476 * @throws DateTimeException if the unit is not supported
477 */
478 @Override
479 public long get(TemporalUnit unit) {
480 if (unit == SECONDS) {
481 return seconds;
482 } else if (unit == NANOS) {
483 return nanos;
484 } else {
485 throw new DateTimeException("Unsupported unit: " + unit.getName());
486 }
487 }
488
489 /**
490 * Gets the set of units supported by this duration.
491 * <p>
492 * The supported units are {@link ChronoUnit#SECONDS SECONDS},
493 * and {@link ChronoUnit#NANOS NANOS}.
494 * They are returned in the order seconds, nanos.
495 * <p>
496 * This set can be used in conjunction with {@link #get(TemporalUnit)}
497 * to access the entire state of the period.
498 *
499 * @return a list containing the seconds and nanos units, not null
500 */
501 @Override
502 public List<TemporalUnit> getUnits() {
503 return DurationUnits.UNITS;
504 }
505
506 /**
507 * Private class to delay initialization of this list until needed.
508 * The circular dependency between Duration and ChronoUnit prevents
509 * the simple initialization in Duration.
510 */
511 private static class DurationUnits {
512 final static List<TemporalUnit> UNITS =
513 Collections.unmodifiableList(Arrays.<TemporalUnit>asList(SECONDS, NANOS));
514 }
515
516 //-----------------------------------------------------------------------
517 /**
518 * Checks if this duration is zero length.
519 * <p>
520 * A {@code Duration} represents a directed distance between two points on
521 * the time-line and can therefore be positive, zero or negative.
522 * This method checks whether the length is zero.
523 *
524 * @return true if this duration has a total length equal to zero
525 */
526 public boolean isZero() {
527 return (seconds | nanos) == 0;
528 }
529
530 /**
531 * Checks if this duration is negative, excluding zero.
532 * <p>
533 * A {@code Duration} represents a directed distance between two points on
534 * the time-line and can therefore be positive, zero or negative.
535 * This method checks whether the length is less than zero.
536 *
537 * @return true if this duration has a total length less than zero
538 */
539 public boolean isNegative() {
540 return seconds < 0;
541 }
542
543 //-----------------------------------------------------------------------
544 /**
545 * Gets the number of seconds in this duration.
546 * <p>
547 * The length of the duration is stored using two fields - seconds and nanoseconds.
562 /**
563 * Gets the number of nanoseconds within the second in this duration.
564 * <p>
565 * The length of the duration is stored using two fields - seconds and nanoseconds.
566 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to
567 * the length in seconds.
568 * The total duration is defined by calling this method and {@link #getSeconds()}.
569 * <p>
570 * A {@code Duration} represents a directed distance between two points on the time-line.
571 * A negative duration is expressed by the negative sign of the seconds part.
572 * A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds.
573 *
574 * @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999
575 */
576 public int getNano() {
577 return nanos;
578 }
579
580 //-----------------------------------------------------------------------
581 /**
582 * Returns a copy of this duration with the specified amount of seconds.
583 * <p>
584 * This returns a duration with the specified seconds, retaining the
585 * nano-of-second part of this duration.
586 * <p>
587 * This instance is immutable and unaffected by this method call.
588 *
589 * @param seconds the seconds to represent, may be negative
590 * @return a {@code Duration} based on this period with the requested seconds, not null
591 */
592 public Duration withSeconds(long seconds) {
593 return create(seconds, nanos);
594 }
595
596 /**
597 * Returns a copy of this duration with the specified nano-of-second.
598 * <p>
599 * This returns a duration with the specified nano-of-second, retaining the
600 * seconds part of this duration.
601 * <p>
602 * This instance is immutable and unaffected by this method call.
603 *
604 * @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999
605 * @return a {@code Duration} based on this period with the requested nano-of-second, not null
606 * @throws DateTimeException if the nano-of-second is invalid
607 */
608 public Duration withNanos(int nanoOfSecond) {
609 NANO_OF_SECOND.checkValidIntValue(nanoOfSecond);
610 return create(seconds, nanoOfSecond);
611 }
612
613 //-----------------------------------------------------------------------
614 /**
615 * Returns a copy of this duration with the specified duration added.
616 * <p>
617 * This instance is immutable and unaffected by this method call.
618 *
619 * @param duration the duration to add, positive or negative, not null
620 * @return a {@code Duration} based on this duration with the specified duration added, not null
621 * @throws ArithmeticException if numeric overflow occurs
622 */
623 public Duration plus(Duration duration) {
624 return plus(duration.getSeconds(), duration.getNano());
625 }
626
627 /**
628 * Returns a copy of this duration with the specified duration added.
629 * <p>
630 * The duration amount is measured in terms of the specified unit.
631 * Only a subset of units are accepted by this method.
632 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or
633 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
634 * <p>
648 throw new DateTimeException("Unit must not have an estimated duration");
649 }
650 if (amountToAdd == 0) {
651 return this;
652 }
653 if (unit instanceof ChronoUnit) {
654 switch ((ChronoUnit) unit) {
655 case NANOS: return plusNanos(amountToAdd);
656 case MICROS: return plusSeconds((amountToAdd / (1000_000L * 1000)) * 1000).plusNanos((amountToAdd % (1000_000L * 1000)) * 1000);
657 case MILLIS: return plusMillis(amountToAdd);
658 case SECONDS: return plusSeconds(amountToAdd);
659 }
660 return plusSeconds(Math.multiplyExact(unit.getDuration().seconds, amountToAdd));
661 }
662 Duration duration = unit.getDuration().multipliedBy(amountToAdd);
663 return plusSeconds(duration.getSeconds()).plusNanos(duration.getNano());
664 }
665
666 //-----------------------------------------------------------------------
667 /**
668 * Returns a copy of this duration with the specified duration in standard 24 hour days added.
669 * <p>
670 * The number of days is multiplied by 86400 to obtain the number of seconds to add.
671 * This is based on the standard definition of a day as 24 hours.
672 * <p>
673 * This instance is immutable and unaffected by this method call.
674 *
675 * @param daysToAdd the days to add, positive or negative
676 * @return a {@code Duration} based on this duration with the specified days added, not null
677 * @throws ArithmeticException if numeric overflow occurs
678 */
679 public Duration plusDays(long daysToAdd) {
680 return plus(Math.multiplyExact(daysToAdd, SECONDS_PER_DAY), 0);
681 }
682
683 /**
684 * Returns a copy of this duration with the specified duration in hours added.
685 * <p>
686 * This instance is immutable and unaffected by this method call.
687 *
688 * @param hoursToAdd the hours to add, positive or negative
689 * @return a {@code Duration} based on this duration with the specified hours added, not null
690 * @throws ArithmeticException if numeric overflow occurs
691 */
692 public Duration plusHours(long hoursToAdd) {
693 return plus(Math.multiplyExact(hoursToAdd, SECONDS_PER_HOUR), 0);
694 }
695
696 /**
697 * Returns a copy of this duration with the specified duration in minutes added.
698 * <p>
699 * This instance is immutable and unaffected by this method call.
700 *
701 * @param minutesToAdd the minutes to add, positive or negative
702 * @return a {@code Duration} based on this duration with the specified minutes added, not null
703 * @throws ArithmeticException if numeric overflow occurs
704 */
705 public Duration plusMinutes(long minutesToAdd) {
706 return plus(Math.multiplyExact(minutesToAdd, SECONDS_PER_MINUTE), 0);
707 }
708
709 /**
710 * Returns a copy of this duration with the specified duration in seconds added.
711 * <p>
712 * This instance is immutable and unaffected by this method call.
713 *
714 * @param secondsToAdd the seconds to add, positive or negative
715 * @return a {@code Duration} based on this duration with the specified seconds added, not null
716 * @throws ArithmeticException if numeric overflow occurs
717 */
718 public Duration plusSeconds(long secondsToAdd) {
719 return plus(secondsToAdd, 0);
720 }
721
722 /**
723 * Returns a copy of this duration with the specified duration in milliseconds added.
724 * <p>
725 * This instance is immutable and unaffected by this method call.
726 *
727 * @param millisToAdd the milliseconds to add, positive or negative
728 * @return a {@code Duration} based on this duration with the specified milliseconds added, not null
729 * @throws ArithmeticException if numeric overflow occurs
789 * Returns a copy of this duration with the specified duration subtracted.
790 * <p>
791 * The duration amount is measured in terms of the specified unit.
792 * Only a subset of units are accepted by this method.
793 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or
794 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
795 * <p>
796 * This instance is immutable and unaffected by this method call.
797 *
798 * @param amountToSubtract the amount of the period, measured in terms of the unit, positive or negative
799 * @param unit the unit that the period is measured in, must have an exact duration, not null
800 * @return a {@code Duration} based on this duration with the specified duration subtracted, not null
801 * @throws ArithmeticException if numeric overflow occurs
802 */
803 public Duration minus(long amountToSubtract, TemporalUnit unit) {
804 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
805 }
806
807 //-----------------------------------------------------------------------
808 /**
809 * Returns a copy of this duration with the specified duration in standard 24 hour days subtracted.
810 * <p>
811 * The number of days is multiplied by 86400 to obtain the number of seconds to subtract.
812 * This is based on the standard definition of a day as 24 hours.
813 * <p>
814 * This instance is immutable and unaffected by this method call.
815 *
816 * @param daysToSubtract the days to subtract, positive or negative
817 * @return a {@code Duration} based on this duration with the specified days subtracted, not null
818 * @throws ArithmeticException if numeric overflow occurs
819 */
820 public Duration minusDays(long daysToSubtract) {
821 return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract));
822 }
823
824 /**
825 * Returns a copy of this duration with the specified duration in hours subtracted.
826 * <p>
827 * The number of hours is multiplied by 3600 to obtain the number of seconds to subtract.
828 * <p>
829 * This instance is immutable and unaffected by this method call.
830 *
831 * @param hoursToSubtract the hours to subtract, positive or negative
832 * @return a {@code Duration} based on this duration with the specified hours subtracted, not null
833 * @throws ArithmeticException if numeric overflow occurs
834 */
835 public Duration minusHours(long hoursToSubtract) {
836 return (hoursToSubtract == Long.MIN_VALUE ? plusHours(Long.MAX_VALUE).plusHours(1) : plusHours(-hoursToSubtract));
837 }
838
839 /**
840 * Returns a copy of this duration with the specified duration in minutes subtracted.
841 * <p>
842 * The number of hours is multiplied by 60 to obtain the number of seconds to subtract.
843 * <p>
844 * This instance is immutable and unaffected by this method call.
845 *
846 * @param minutesToSubtract the minutes to subtract, positive or negative
847 * @return a {@code Duration} based on this duration with the specified minutes subtracted, not null
848 * @throws ArithmeticException if numeric overflow occurs
849 */
850 public Duration minusMinutes(long minutesToSubtract) {
851 return (minutesToSubtract == Long.MIN_VALUE ? plusMinutes(Long.MAX_VALUE).plusMinutes(1) : plusMinutes(-minutesToSubtract));
852 }
853
854 /**
855 * Returns a copy of this duration with the specified duration in seconds subtracted.
856 * <p>
857 * This instance is immutable and unaffected by this method call.
858 *
859 * @param secondsToSubtract the seconds to subtract, positive or negative
860 * @return a {@code Duration} based on this duration with the specified seconds subtracted, not null
861 * @throws ArithmeticException if numeric overflow occurs
862 */
863 public Duration minusSeconds(long secondsToSubtract) {
864 return (secondsToSubtract == Long.MIN_VALUE ? plusSeconds(Long.MAX_VALUE).plusSeconds(1) : plusSeconds(-secondsToSubtract));
865 }
866
867 /**
868 * Returns a copy of this duration with the specified duration in milliseconds subtracted.
869 * <p>
870 * This instance is immutable and unaffected by this method call.
871 *
872 * @param millisToSubtract the milliseconds to subtract, positive or negative
873 * @return a {@code Duration} based on this duration with the specified milliseconds subtracted, not null
874 * @throws ArithmeticException if numeric overflow occurs
900 * @return a {@code Duration} based on this duration multiplied by the specified scalar, not null
901 * @throws ArithmeticException if numeric overflow occurs
902 */
903 public Duration multipliedBy(long multiplicand) {
904 if (multiplicand == 0) {
905 return ZERO;
906 }
907 if (multiplicand == 1) {
908 return this;
909 }
910 return create(toSeconds().multiply(BigDecimal.valueOf(multiplicand)));
911 }
912
913 /**
914 * Returns a copy of this duration divided by the specified value.
915 * <p>
916 * This instance is immutable and unaffected by this method call.
917 *
918 * @param divisor the value to divide the duration by, positive or negative, not zero
919 * @return a {@code Duration} based on this duration divided by the specified divisor, not null
920 * @throws ArithmeticException if the divisor is zero or if numeric overflow occurs
921 */
922 public Duration dividedBy(long divisor) {
923 if (divisor == 0) {
924 throw new ArithmeticException("Cannot divide by zero");
925 }
926 if (divisor == 1) {
927 return this;
928 }
929 return create(toSeconds().divide(BigDecimal.valueOf(divisor), RoundingMode.DOWN));
930 }
931
932 /**
933 * Converts this duration to the total length in seconds and
934 * fractional nanoseconds expressed as a {@code BigDecimal}.
935 *
936 * @return the total length of the duration in seconds, with a scale of 9, not null
937 */
938 private BigDecimal toSeconds() {
939 return BigDecimal.valueOf(seconds).add(BigDecimal.valueOf(nanos, 9));
940 }
977 * This method returns a positive duration by effectively removing the sign from any negative total length.
978 * For example, {@code PT-1.3S} will be returned as {@code PT1.3S}.
979 * <p>
980 * This instance is immutable and unaffected by this method call.
981 *
982 * @return a {@code Duration} based on this duration with an absolute length, not null
983 * @throws ArithmeticException if numeric overflow occurs
984 */
985 public Duration abs() {
986 return isNegative() ? negated() : this;
987 }
988
989 //-------------------------------------------------------------------------
990 /**
991 * Adds this duration to the specified temporal object.
992 * <p>
993 * This returns a temporal object of the same observable type as the input
994 * with this duration added.
995 * <p>
996 * In most cases, it is clearer to reverse the calling pattern by using
997 * {@link Temporal#plus(TemporalAmount)}.
998 * <pre>
999 * // these two lines are equivalent, but the second approach is recommended
1000 * dateTime = thisDuration.addTo(dateTime);
1001 * dateTime = dateTime.plus(thisDuration);
1002 * </pre>
1003 * <p>
1004 * The calculation will add the seconds, then nanos.
1005 * Only non-zero amounts will be added.
1006 * <p>
1007 * This instance is immutable and unaffected by this method call.
1008 *
1009 * @param temporal the temporal object to adjust, not null
1010 * @return an object of the same type with the adjustment made, not null
1011 * @throws DateTimeException if unable to add
1012 * @throws ArithmeticException if numeric overflow occurs
1013 */
1014 @Override
1015 public Temporal addTo(Temporal temporal) {
1016 if (seconds != 0) {
1017 temporal = temporal.plus(seconds, SECONDS);
1018 }
1019 if (nanos != 0) {
1020 temporal = temporal.plus(nanos, NANOS);
1021 }
1022 return temporal;
1023 }
1024
1025 /**
1026 * Subtracts this duration from the specified temporal object.
1027 * <p>
1028 * This returns a temporal object of the same observable type as the input
1029 * with this duration subtracted.
1030 * <p>
1031 * In most cases, it is clearer to reverse the calling pattern by using
1032 * {@link Temporal#minus(TemporalAmount)}.
1033 * <pre>
1034 * // these two lines are equivalent, but the second approach is recommended
1035 * dateTime = thisDuration.subtractFrom(dateTime);
1036 * dateTime = dateTime.minus(thisDuration);
1037 * </pre>
1038 * <p>
1039 * The calculation will subtract the seconds, then nanos.
1040 * Only non-zero amounts will be added.
1041 * <p>
1042 * This instance is immutable and unaffected by this method call.
1043 *
1044 * @param temporal the temporal object to adjust, not null
1045 * @return an object of the same type with the adjustment made, not null
1046 * @throws DateTimeException if unable to subtract
1047 * @throws ArithmeticException if numeric overflow occurs
1048 */
1049 @Override
1050 public Temporal subtractFrom(Temporal temporal) {
1051 if (seconds != 0) {
1052 temporal = temporal.minus(seconds, SECONDS);
1053 }
1054 if (nanos != 0) {
1055 temporal = temporal.minus(nanos, NANOS);
1056 }
1057 return temporal;
1058 }
1059
1060 //-----------------------------------------------------------------------
1061 /**
1062 * Gets the number of minutes in this duration.
1063 * <p>
1064 * This returns the total number of minutes in the duration by dividing the
1065 * number of seconds by 86400.
1066 * This is based on the standard definition of a day as 24 hours.
1067 * <p>
1068 * This instance is immutable and unaffected by this method call.
1069 *
1070 * @return the number of minutes in the duration, may be negative
1071 */
1072 public long toDays() {
1073 return seconds / SECONDS_PER_DAY;
1074 }
1075
1076 /**
1077 * Gets the number of minutes in this duration.
1078 * <p>
1079 * This returns the total number of minutes in the duration by dividing the
1080 * number of seconds by 3600.
1081 * <p>
1082 * This instance is immutable and unaffected by this method call.
1083 *
1084 * @return the number of minutes in the duration, may be negative
1085 */
1086 public long toHours() {
1087 return seconds / SECONDS_PER_HOUR;
1088 }
1089
1090 /**
1091 * Gets the number of minutes in this duration.
1092 * <p>
1093 * This returns the total number of minutes in the duration by dividing the
1094 * number of seconds by 60.
1095 * <p>
1096 * This instance is immutable and unaffected by this method call.
1097 *
1098 * @return the number of minutes in the duration, may be negative
1099 */
1100 public long toMinutes() {
1101 return seconds / SECONDS_PER_MINUTE;
1102 }
1103
1104 /**
1105 * Converts this duration to the total length in milliseconds.
1106 * <p>
1107 * If this duration is too large to fit in a {@code long} milliseconds, then an
1108 * exception is thrown.
1109 * <p>
1110 * If this duration has greater than millisecond precision, then the conversion
1111 * will drop any excess precision information as though the amount in nanoseconds
1112 * was subject to integer division by one million.
1113 *
1114 * @return the total length of the duration in milliseconds
1115 * @throws ArithmeticException if numeric overflow occurs
1116 */
1117 public long toMillis() {
1118 long millis = Math.multiplyExact(seconds, 1000);
1119 millis = Math.addExact(millis, nanos / 1000_000);
1120 return millis;
1121 }
1122
1123 /**
1124 * Converts this duration to the total length in nanoseconds expressed as a {@code long}.
1125 * <p>
1126 * If this duration is too large to fit in a {@code long} nanoseconds, then an
1127 * exception is thrown.
1128 *
1129 * @return the total length of the duration in nanoseconds
1130 * @throws ArithmeticException if numeric overflow occurs
1131 */
1132 public long toNanos() {
1133 long millis = Math.multiplyExact(seconds, NANOS_PER_SECOND);
1134 millis = Math.addExact(millis, nanos);
1135 return millis;
1136 }
1137
1138 //-----------------------------------------------------------------------
1139 /**
1140 * Compares this duration to the specified {@code Duration}.
1141 * <p>
1142 * The comparison is based on the total length of the durations.
1143 * It is "consistent with equals", as defined by {@link Comparable}.
1144 *
1145 * @param otherDuration the other duration to compare to, not null
1146 * @return the comparator value, negative if less, positive if greater
1147 */
1148 @Override
1149 public int compareTo(Duration otherDuration) {
1150 int cmp = Long.compare(seconds, otherDuration.seconds);
1151 if (cmp != 0) {
1152 return cmp;
1153 }
1154 return nanos - otherDuration.nanos;
1155 }
1156
1157 //-----------------------------------------------------------------------
1158 /**
1159 * Checks if this duration is equal to the specified {@code Duration}.
1160 * <p>
1161 * The comparison is based on the total length of the durations.
1162 *
1163 * @param otherDuration the other duration, null returns false
1164 * @return true if the other duration is equal to this one
1165 */
1166 @Override
1167 public boolean equals(Object otherDuration) {
1168 if (this == otherDuration) {
1169 return true;
1170 }
1171 if (otherDuration instanceof Duration) {
1172 Duration other = (Duration) otherDuration;
1173 return this.seconds == other.seconds &&
1174 this.nanos == other.nanos;
1175 }
1176 return false;
1177 }
1178
1179 /**
1180 * A hash code for this duration.
1181 *
1182 * @return a suitable hash code
1183 */
1184 @Override
1185 public int hashCode() {
1186 return ((int) (seconds ^ (seconds >>> 32))) + (51 * nanos);
1187 }
1188
1189 //-----------------------------------------------------------------------
1190 /**
1191 * A string representation of this duration using ISO-8601 seconds
1192 * based representation, such as {@code PT8H6M12.345S}.
1193 * <p>
1194 * The format of the returned string will be {@code PTnHnMnS}, where n is
1195 * the relevant hours, minutes or seconds part of the duration.
1196 * Any fractional seconds are placed after a decimal point i the seconds section.
1197 * If a section has a zero value, it is omitted.
1198 * The hours, minutes and seconds will all have the same sign.
1199 * <p>
1200 * Examples:
1201 * <pre>
1202 * "20.345 seconds" -> "PT20.345S
1203 * "15 minutes" (15 * 60 seconds) -> "PT15M"
1204 * "10 hours" (10 * 3600 seconds) -> "PT10H"
1205 * "2 days" (2 * 86400 seconds) -> "PT48H"
1206 * </pre>
1207 * Note that multiples of 24 hours are not output as days to avoid confusion
1208 * with {@code Period}.
1209 *
1210 * @return an ISO-8601 representation of this duration, not null
1211 */
1212 @Override
1213 public String toString() {
1214 if (this == ZERO) {
1215 return "PT0S";
1216 }
1217 long hours = seconds / SECONDS_PER_HOUR;
1218 int minutes = (int) ((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
1219 int secs = (int) (seconds % SECONDS_PER_MINUTE);
1220 StringBuilder buf = new StringBuilder(24);
1221 buf.append("PT");
1222 if (hours != 0) {
1223 buf.append(hours).append('H');
1224 }
1225 if (minutes != 0) {
1226 buf.append(minutes).append('M');
1227 }
1228 if (secs == 0 && nanos == 0 && buf.length() > 2) {
1229 return buf.toString();
1230 }
1231 if (secs < 0 && nanos > 0) {
1232 if (secs == -1) {
1233 buf.append("-0");
1234 } else {
1235 buf.append(secs + 1);
1236 }
1237 } else {
1238 buf.append(secs);
1239 }
1240 if (nanos > 0) {
1241 int pos = buf.length();
1242 if (secs < 0) {
1243 buf.append(2 * NANOS_PER_SECOND - nanos);
1244 } else {
1245 buf.append(nanos + NANOS_PER_SECOND);
1246 }
1247 while (buf.charAt(buf.length() - 1) == '0') {
1248 buf.setLength(buf.length() - 1);
1249 }
1250 buf.setCharAt(pos, '.');
1251 }
1252 buf.append('S');
1253 return buf.toString();
1254 }
1255
1256 //-----------------------------------------------------------------------
1257 /**
1258 * Writes the object using a
1259 * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1260 * <pre>
1261 * out.writeByte(1); // identifies this as a Duration
1262 * out.writeLong(seconds);
|