1 /* 2 * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 /* 27 * This file is available under and governed by the GNU General Public 28 * License version 2 only, as published by the Free Software Foundation. 29 * However, the following notice accompanied the original version of this 30 * file: 31 * 32 * Copyright (c) 2007-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.LocalTime.MINUTES_PER_HOUR; 65 import static java.time.LocalTime.NANOS_PER_MILLI; 66 import static java.time.LocalTime.NANOS_PER_SECOND; 67 import static java.time.LocalTime.SECONDS_PER_DAY; 68 import static java.time.LocalTime.SECONDS_PER_HOUR; 69 import static java.time.LocalTime.SECONDS_PER_MINUTE; 70 import static java.time.temporal.ChronoField.NANO_OF_SECOND; 71 import static java.time.temporal.ChronoUnit.DAYS; 72 import static java.time.temporal.ChronoUnit.NANOS; 73 import static java.time.temporal.ChronoUnit.SECONDS; 74 75 import java.io.DataInput; 76 import java.io.DataOutput; 77 import java.io.IOException; 78 import java.io.InvalidObjectException; 79 import java.io.ObjectInputStream; 80 import java.io.Serializable; 81 import java.math.BigDecimal; 82 import java.math.BigInteger; 83 import java.math.RoundingMode; 84 import java.time.format.DateTimeParseException; 85 import java.time.temporal.ChronoField; 86 import java.time.temporal.ChronoUnit; 87 import java.time.temporal.Temporal; 88 import java.time.temporal.TemporalAmount; 89 import java.time.temporal.TemporalUnit; 90 import java.time.temporal.UnsupportedTemporalTypeException; 91 import java.util.Arrays; 92 import java.util.Collections; 93 import java.util.List; 94 import java.util.Objects; 95 import java.util.regex.Matcher; 96 import java.util.regex.Pattern; 97 98 // Android-changed: removed ValueBased paragraph. 99 /** 100 * A time-based amount of time, such as '34.5 seconds'. 101 * <p> 102 * This class models a quantity or amount of time in terms of seconds and nanoseconds. 103 * It can be accessed using other duration-based units, such as minutes and hours. 104 * In addition, the {@link ChronoUnit#DAYS DAYS} unit can be used and is treated as 105 * exactly equal to 24 hours, thus ignoring daylight savings effects. 106 * See {@link Period} for the date-based equivalent to this class. 107 * <p> 108 * A physical duration could be of infinite length. 109 * For practicality, the duration is stored with constraints similar to {@link Instant}. 110 * The duration uses nanosecond resolution with a maximum value of the seconds that can 111 * be held in a {@code long}. This is greater than the current estimated age of the universe. 112 * <p> 113 * The range of a duration requires the storage of a number larger than a {@code long}. 114 * To achieve this, the class stores a {@code long} representing seconds and an {@code int} 115 * representing nanosecond-of-second, which will always be between 0 and 999,999,999. 116 * The model is of a directed duration, meaning that the duration may be negative. 117 * <p> 118 * The duration is measured in "seconds", but these are not necessarily identical to 119 * the scientific "SI second" definition based on atomic clocks. 120 * This difference only impacts durations measured near a leap-second and should not affect 121 * most applications. 122 * See {@link Instant} for a discussion as to the meaning of the second and time-scales. 123 * 124 * @implSpec 125 * This class is immutable and thread-safe. 126 * 127 * @since 1.8 128 */ 129 public final class Duration 130 implements TemporalAmount, Comparable<Duration>, Serializable { 131 132 /** 133 * Constant for a duration of zero. 134 */ 135 public static final Duration ZERO = new Duration(0, 0); 136 /** 137 * Serialization version. 138 */ 139 @java.io.Serial 140 private static final long serialVersionUID = 3078945930695997490L; 141 /** 142 * Constant for nanos per second. 143 */ 144 private static final BigInteger BI_NANOS_PER_SECOND = BigInteger.valueOf(NANOS_PER_SECOND); 145 /** 146 * The pattern for parsing. 147 */ 148 private static final Pattern PATTERN = 149 Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)D)?" + 150 "(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]{0,9}))?S)?)?", 151 Pattern.CASE_INSENSITIVE); 152 153 /** 154 * The number of seconds in the duration. 155 */ 156 private final long seconds; 157 /** 158 * The number of nanoseconds in the duration, expressed as a fraction of the 159 * number of seconds. This is always positive, and never exceeds 999,999,999. 160 */ 161 private final int nanos; 162 163 //----------------------------------------------------------------------- 164 /** 165 * Obtains a {@code Duration} representing a number of standard 24 hour days. 166 * <p> 167 * The seconds are calculated based on the standard definition of a day, 168 * where each day is 86400 seconds which implies a 24 hour day. 169 * The nanosecond in second field is set to zero. 170 * 171 * @param days the number of days, positive or negative 172 * @return a {@code Duration}, not null 173 * @throws ArithmeticException if the input days exceeds the capacity of {@code Duration} 174 */ ofDays(long days)175 public static Duration ofDays(long days) { 176 return create(Math.multiplyExact(days, SECONDS_PER_DAY), 0); 177 } 178 179 /** 180 * Obtains a {@code Duration} representing a number of standard hours. 181 * <p> 182 * The seconds are calculated based on the standard definition of an hour, 183 * where each hour is 3600 seconds. 184 * The nanosecond in second field is set to zero. 185 * 186 * @param hours the number of hours, positive or negative 187 * @return a {@code Duration}, not null 188 * @throws ArithmeticException if the input hours exceeds the capacity of {@code Duration} 189 */ ofHours(long hours)190 public static Duration ofHours(long hours) { 191 return create(Math.multiplyExact(hours, SECONDS_PER_HOUR), 0); 192 } 193 194 /** 195 * Obtains a {@code Duration} representing a number of standard minutes. 196 * <p> 197 * The seconds are calculated based on the standard definition of a minute, 198 * where each minute is 60 seconds. 199 * The nanosecond in second field is set to zero. 200 * 201 * @param minutes the number of minutes, positive or negative 202 * @return a {@code Duration}, not null 203 * @throws ArithmeticException if the input minutes exceeds the capacity of {@code Duration} 204 */ ofMinutes(long minutes)205 public static Duration ofMinutes(long minutes) { 206 return create(Math.multiplyExact(minutes, SECONDS_PER_MINUTE), 0); 207 } 208 209 //----------------------------------------------------------------------- 210 /** 211 * Obtains a {@code Duration} representing a number of seconds. 212 * <p> 213 * The nanosecond in second field is set to zero. 214 * 215 * @param seconds the number of seconds, positive or negative 216 * @return a {@code Duration}, not null 217 */ ofSeconds(long seconds)218 public static Duration ofSeconds(long seconds) { 219 return create(seconds, 0); 220 } 221 222 /** 223 * Obtains a {@code Duration} representing a number of seconds and an 224 * adjustment in nanoseconds. 225 * <p> 226 * This method allows an arbitrary number of nanoseconds to be passed in. 227 * The factory will alter the values of the second and nanosecond in order 228 * to ensure that the stored nanosecond is in the range 0 to 999,999,999. 229 * For example, the following will result in exactly the same duration: 230 * <pre> 231 * Duration.ofSeconds(3, 1); 232 * Duration.ofSeconds(4, -999_999_999); 233 * Duration.ofSeconds(2, 1000_000_001); 234 * </pre> 235 * 236 * @param seconds the number of seconds, positive or negative 237 * @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative 238 * @return a {@code Duration}, not null 239 * @throws ArithmeticException if the adjustment causes the seconds to exceed the capacity of {@code Duration} 240 */ ofSeconds(long seconds, long nanoAdjustment)241 public static Duration ofSeconds(long seconds, long nanoAdjustment) { 242 long secs = Math.addExact(seconds, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND)); 243 int nos = (int) Math.floorMod(nanoAdjustment, NANOS_PER_SECOND); 244 return create(secs, nos); 245 } 246 247 //----------------------------------------------------------------------- 248 /** 249 * Obtains a {@code Duration} representing a number of milliseconds. 250 * <p> 251 * The seconds and nanoseconds are extracted from the specified milliseconds. 252 * 253 * @param millis the number of milliseconds, positive or negative 254 * @return a {@code Duration}, not null 255 */ ofMillis(long millis)256 public static Duration ofMillis(long millis) { 257 long secs = millis / 1000; 258 int mos = (int) (millis % 1000); 259 if (mos < 0) { 260 mos += 1000; 261 secs--; 262 } 263 return create(secs, mos * 1000_000); 264 } 265 266 //----------------------------------------------------------------------- 267 /** 268 * Obtains a {@code Duration} representing a number of nanoseconds. 269 * <p> 270 * The seconds and nanoseconds are extracted from the specified nanoseconds. 271 * 272 * @param nanos the number of nanoseconds, positive or negative 273 * @return a {@code Duration}, not null 274 */ ofNanos(long nanos)275 public static Duration ofNanos(long nanos) { 276 long secs = nanos / NANOS_PER_SECOND; 277 int nos = (int) (nanos % NANOS_PER_SECOND); 278 if (nos < 0) { 279 nos += NANOS_PER_SECOND; 280 secs--; 281 } 282 return create(secs, nos); 283 } 284 285 //----------------------------------------------------------------------- 286 /** 287 * Obtains a {@code Duration} representing an amount in the specified unit. 288 * <p> 289 * The parameters represent the two parts of a phrase like '6 Hours'. For example: 290 * <pre> 291 * Duration.of(3, SECONDS); 292 * Duration.of(465, HOURS); 293 * </pre> 294 * Only a subset of units are accepted by this method. 295 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or 296 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception. 297 * 298 * @param amount the amount of the duration, measured in terms of the unit, positive or negative 299 * @param unit the unit that the duration is measured in, must have an exact duration, not null 300 * @return a {@code Duration}, not null 301 * @throws DateTimeException if the period unit has an estimated duration 302 * @throws ArithmeticException if a numeric overflow occurs 303 */ of(long amount, TemporalUnit unit)304 public static Duration of(long amount, TemporalUnit unit) { 305 return ZERO.plus(amount, unit); 306 } 307 308 //----------------------------------------------------------------------- 309 /** 310 * Obtains an instance of {@code Duration} from a temporal amount. 311 * <p> 312 * This obtains a duration based on the specified amount. 313 * A {@code TemporalAmount} represents an amount of time, which may be 314 * date-based or time-based, which this factory extracts to a duration. 315 * <p> 316 * The conversion loops around the set of units from the amount and uses 317 * the {@linkplain TemporalUnit#getDuration() duration} of the unit to 318 * calculate the total {@code Duration}. 319 * Only a subset of units are accepted by this method. The unit must either 320 * have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} 321 * or be {@link ChronoUnit#DAYS} which is treated as 24 hours. 322 * If any other units are found then an exception is thrown. 323 * 324 * @param amount the temporal amount to convert, not null 325 * @return the equivalent duration, not null 326 * @throws DateTimeException if unable to convert to a {@code Duration} 327 * @throws ArithmeticException if numeric overflow occurs 328 */ from(TemporalAmount amount)329 public static Duration from(TemporalAmount amount) { 330 Objects.requireNonNull(amount, "amount"); 331 Duration duration = ZERO; 332 for (TemporalUnit unit : amount.getUnits()) { 333 duration = duration.plus(amount.get(unit), unit); 334 } 335 return duration; 336 } 337 338 //----------------------------------------------------------------------- 339 /** 340 * Obtains a {@code Duration} from a text string such as {@code PnDTnHnMn.nS}. 341 * <p> 342 * This will parse a textual representation of a duration, including the 343 * string produced by {@code toString()}. The formats accepted are based 344 * on the ISO-8601 duration format {@code PnDTnHnMn.nS} with days 345 * considered to be exactly 24 hours. 346 * <p> 347 * The string starts with an optional sign, denoted by the ASCII negative 348 * or positive symbol. If negative, the whole period is negated. 349 * The ASCII letter "P" is next in upper or lower case. 350 * There are then four sections, each consisting of a number and a suffix. 351 * The sections have suffixes in ASCII of "D", "H", "M" and "S" for 352 * days, hours, minutes and seconds, accepted in upper or lower case. 353 * The suffixes must occur in order. The ASCII letter "T" must occur before 354 * the first occurrence, if any, of an hour, minute or second section. 355 * At least one of the four sections must be present, and if "T" is present 356 * there must be at least one section after the "T". 357 * The number part of each section must consist of one or more ASCII digits. 358 * The number may be prefixed by the ASCII negative or positive symbol. 359 * The number of days, hours and minutes must parse to an {@code long}. 360 * The number of seconds must parse to an {@code long} with optional fraction. 361 * The decimal point may be either a dot or a comma. 362 * The fractional part may have from zero to 9 digits. 363 * <p> 364 * The leading plus/minus sign, and negative values for other units are 365 * not part of the ISO-8601 standard. 366 * <p> 367 * Examples: 368 * <pre> 369 * "PT20.345S" -- parses as "20.345 seconds" 370 * "PT15M" -- parses as "15 minutes" (where a minute is 60 seconds) 371 * "PT10H" -- parses as "10 hours" (where an hour is 3600 seconds) 372 * "P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds) 373 * "P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes" 374 * "P-6H3M" -- parses as "-6 hours and +3 minutes" 375 * "-P6H3M" -- parses as "-6 hours and -3 minutes" 376 * "-P-6H+3M" -- parses as "+6 hours and -3 minutes" 377 * </pre> 378 * 379 * @param text the text to parse, not null 380 * @return the parsed duration, not null 381 * @throws DateTimeParseException if the text cannot be parsed to a duration 382 */ parse(CharSequence text)383 public static Duration parse(CharSequence text) { 384 Objects.requireNonNull(text, "text"); 385 Matcher matcher = PATTERN.matcher(text); 386 if (matcher.matches()) { 387 // check for letter T but no time sections 388 if ("T".equals(matcher.group(3)) == false) { 389 boolean negate = "-".equals(matcher.group(1)); 390 String dayMatch = matcher.group(2); 391 String hourMatch = matcher.group(4); 392 String minuteMatch = matcher.group(5); 393 String secondMatch = matcher.group(6); 394 String fractionMatch = matcher.group(7); 395 if (dayMatch != null || hourMatch != null || minuteMatch != null || secondMatch != null) { 396 long daysAsSecs = parseNumber(text, dayMatch, SECONDS_PER_DAY, "days"); 397 long hoursAsSecs = parseNumber(text, hourMatch, SECONDS_PER_HOUR, "hours"); 398 long minsAsSecs = parseNumber(text, minuteMatch, SECONDS_PER_MINUTE, "minutes"); 399 long seconds = parseNumber(text, secondMatch, 1, "seconds"); 400 int nanos = parseFraction(text, fractionMatch, seconds < 0 ? -1 : 1); 401 try { 402 return create(negate, daysAsSecs, hoursAsSecs, minsAsSecs, seconds, nanos); 403 } catch (ArithmeticException ex) { 404 throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: overflow", text, 0).initCause(ex); 405 } 406 } 407 } 408 } 409 throw new DateTimeParseException("Text cannot be parsed to a Duration", text, 0); 410 } 411 parseNumber(CharSequence text, String parsed, int multiplier, String errorText)412 private static long parseNumber(CharSequence text, String parsed, int multiplier, String errorText) { 413 // regex limits to [-+]?[0-9]+ 414 if (parsed == null) { 415 return 0; 416 } 417 try { 418 long val = Long.parseLong(parsed); 419 return Math.multiplyExact(val, multiplier); 420 } catch (NumberFormatException | ArithmeticException ex) { 421 throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: " + errorText, text, 0).initCause(ex); 422 } 423 } 424 parseFraction(CharSequence text, String parsed, int negate)425 private static int parseFraction(CharSequence text, String parsed, int negate) { 426 // regex limits to [0-9]{0,9} 427 if (parsed == null || parsed.length() == 0) { 428 return 0; 429 } 430 try { 431 parsed = (parsed + "000000000").substring(0, 9); 432 return Integer.parseInt(parsed) * negate; 433 } catch (NumberFormatException | ArithmeticException ex) { 434 throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: fraction", text, 0).initCause(ex); 435 } 436 } 437 create(boolean negate, long daysAsSecs, long hoursAsSecs, long minsAsSecs, long secs, int nanos)438 private static Duration create(boolean negate, long daysAsSecs, long hoursAsSecs, long minsAsSecs, long secs, int nanos) { 439 long seconds = Math.addExact(daysAsSecs, Math.addExact(hoursAsSecs, Math.addExact(minsAsSecs, secs))); 440 if (negate) { 441 return ofSeconds(seconds, nanos).negated(); 442 } 443 return ofSeconds(seconds, nanos); 444 } 445 446 //----------------------------------------------------------------------- 447 /** 448 * Obtains a {@code Duration} representing the duration between two temporal objects. 449 * <p> 450 * This calculates the duration between two temporal objects. If the objects 451 * are of different types, then the duration is calculated based on the type 452 * of the first object. For example, if the first argument is a {@code LocalTime} 453 * then the second argument is converted to a {@code LocalTime}. 454 * <p> 455 * The specified temporal objects must support the {@link ChronoUnit#SECONDS SECONDS} unit. 456 * For full accuracy, either the {@link ChronoUnit#NANOS NANOS} unit or the 457 * {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} field should be supported. 458 * <p> 459 * The result of this method can be a negative period if the end is before the start. 460 * To guarantee to obtain a positive duration call {@link #abs()} on the result. 461 * 462 * @param startInclusive the start instant, inclusive, not null 463 * @param endExclusive the end instant, exclusive, not null 464 * @return a {@code Duration}, not null 465 * @throws DateTimeException if the seconds between the temporals cannot be obtained 466 * @throws ArithmeticException if the calculation exceeds the capacity of {@code Duration} 467 */ between(Temporal startInclusive, Temporal endExclusive)468 public static Duration between(Temporal startInclusive, Temporal endExclusive) { 469 try { 470 return ofNanos(startInclusive.until(endExclusive, NANOS)); 471 } catch (DateTimeException | ArithmeticException ex) { 472 long secs = startInclusive.until(endExclusive, SECONDS); 473 long nanos; 474 try { 475 nanos = endExclusive.getLong(NANO_OF_SECOND) - startInclusive.getLong(NANO_OF_SECOND); 476 if (secs > 0 && nanos < 0) { 477 secs++; 478 } else if (secs < 0 && nanos > 0) { 479 secs--; 480 } 481 } catch (DateTimeException ex2) { 482 nanos = 0; 483 } 484 return ofSeconds(secs, nanos); 485 } 486 } 487 488 //----------------------------------------------------------------------- 489 /** 490 * Obtains an instance of {@code Duration} using seconds and nanoseconds. 491 * 492 * @param seconds the length of the duration in seconds, positive or negative 493 * @param nanoAdjustment the nanosecond adjustment within the second, from 0 to 999,999,999 494 */ create(long seconds, int nanoAdjustment)495 private static Duration create(long seconds, int nanoAdjustment) { 496 if ((seconds | nanoAdjustment) == 0) { 497 return ZERO; 498 } 499 return new Duration(seconds, nanoAdjustment); 500 } 501 502 /** 503 * Constructs an instance of {@code Duration} using seconds and nanoseconds. 504 * 505 * @param seconds the length of the duration in seconds, positive or negative 506 * @param nanos the nanoseconds within the second, from 0 to 999,999,999 507 */ Duration(long seconds, int nanos)508 private Duration(long seconds, int nanos) { 509 super(); 510 this.seconds = seconds; 511 this.nanos = nanos; 512 } 513 514 //----------------------------------------------------------------------- 515 /** 516 * Gets the value of the requested unit. 517 * <p> 518 * This returns a value for each of the two supported units, 519 * {@link ChronoUnit#SECONDS SECONDS} and {@link ChronoUnit#NANOS NANOS}. 520 * All other units throw an exception. 521 * 522 * @param unit the {@code TemporalUnit} for which to return the value 523 * @return the long value of the unit 524 * @throws DateTimeException if the unit is not supported 525 * @throws UnsupportedTemporalTypeException if the unit is not supported 526 */ 527 @Override get(TemporalUnit unit)528 public long get(TemporalUnit unit) { 529 if (unit == SECONDS) { 530 return seconds; 531 } else if (unit == NANOS) { 532 return nanos; 533 } else { 534 throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); 535 } 536 } 537 538 /** 539 * Gets the set of units supported by this duration. 540 * <p> 541 * The supported units are {@link ChronoUnit#SECONDS SECONDS}, 542 * and {@link ChronoUnit#NANOS NANOS}. 543 * They are returned in the order seconds, nanos. 544 * <p> 545 * This set can be used in conjunction with {@link #get(TemporalUnit)} 546 * to access the entire state of the duration. 547 * 548 * @return a list containing the seconds and nanos units, not null 549 */ 550 @Override getUnits()551 public List<TemporalUnit> getUnits() { 552 return DurationUnits.UNITS; 553 } 554 555 /** 556 * Private class to delay initialization of this list until needed. 557 * The circular dependency between Duration and ChronoUnit prevents 558 * the simple initialization in Duration. 559 */ 560 private static class DurationUnits { 561 static final List<TemporalUnit> UNITS = 562 Collections.unmodifiableList(Arrays.<TemporalUnit>asList(SECONDS, NANOS)); 563 } 564 565 //----------------------------------------------------------------------- 566 /** 567 * Checks if this duration is zero length. 568 * <p> 569 * A {@code Duration} represents a directed distance between two points on 570 * the time-line and can therefore be positive, zero or negative. 571 * This method checks whether the length is zero. 572 * 573 * @return true if this duration has a total length equal to zero 574 */ isZero()575 public boolean isZero() { 576 return (seconds | nanos) == 0; 577 } 578 579 /** 580 * Checks if this duration is negative, excluding zero. 581 * <p> 582 * A {@code Duration} represents a directed distance between two points on 583 * the time-line and can therefore be positive, zero or negative. 584 * This method checks whether the length is less than zero. 585 * 586 * @return true if this duration has a total length less than zero 587 */ isNegative()588 public boolean isNegative() { 589 return seconds < 0; 590 } 591 592 //----------------------------------------------------------------------- 593 /** 594 * Gets the number of seconds in this duration. 595 * <p> 596 * The length of the duration is stored using two fields - seconds and nanoseconds. 597 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to 598 * the length in seconds. 599 * The total duration is defined by calling this method and {@link #getNano()}. 600 * <p> 601 * A {@code Duration} represents a directed distance between two points on the time-line. 602 * A negative duration is expressed by the negative sign of the seconds part. 603 * A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds. 604 * 605 * @return the whole seconds part of the length of the duration, positive or negative 606 */ getSeconds()607 public long getSeconds() { 608 return seconds; 609 } 610 611 /** 612 * Gets the number of nanoseconds within the second in this duration. 613 * <p> 614 * The length of the duration is stored using two fields - seconds and nanoseconds. 615 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to 616 * the length in seconds. 617 * The total duration is defined by calling this method and {@link #getSeconds()}. 618 * <p> 619 * A {@code Duration} represents a directed distance between two points on the time-line. 620 * A negative duration is expressed by the negative sign of the seconds part. 621 * A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds. 622 * 623 * @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999 624 */ getNano()625 public int getNano() { 626 return nanos; 627 } 628 629 //----------------------------------------------------------------------- 630 /** 631 * Returns a copy of this duration with the specified amount of seconds. 632 * <p> 633 * This returns a duration with the specified seconds, retaining the 634 * nano-of-second part of this duration. 635 * <p> 636 * This instance is immutable and unaffected by this method call. 637 * 638 * @param seconds the seconds to represent, may be negative 639 * @return a {@code Duration} based on this period with the requested seconds, not null 640 */ withSeconds(long seconds)641 public Duration withSeconds(long seconds) { 642 return create(seconds, nanos); 643 } 644 645 /** 646 * Returns a copy of this duration with the specified nano-of-second. 647 * <p> 648 * This returns a duration with the specified nano-of-second, retaining the 649 * seconds part of this duration. 650 * <p> 651 * This instance is immutable and unaffected by this method call. 652 * 653 * @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999 654 * @return a {@code Duration} based on this period with the requested nano-of-second, not null 655 * @throws DateTimeException if the nano-of-second is invalid 656 */ withNanos(int nanoOfSecond)657 public Duration withNanos(int nanoOfSecond) { 658 NANO_OF_SECOND.checkValidIntValue(nanoOfSecond); 659 return create(seconds, nanoOfSecond); 660 } 661 662 //----------------------------------------------------------------------- 663 /** 664 * Returns a copy of this duration with the specified duration added. 665 * <p> 666 * This instance is immutable and unaffected by this method call. 667 * 668 * @param duration the duration to add, positive or negative, not null 669 * @return a {@code Duration} based on this duration with the specified duration added, not null 670 * @throws ArithmeticException if numeric overflow occurs 671 */ plus(Duration duration)672 public Duration plus(Duration duration) { 673 return plus(duration.getSeconds(), duration.getNano()); 674 } 675 676 /** 677 * Returns a copy of this duration with the specified duration added. 678 * <p> 679 * The duration amount is measured in terms of the specified unit. 680 * Only a subset of units are accepted by this method. 681 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or 682 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception. 683 * <p> 684 * This instance is immutable and unaffected by this method call. 685 * 686 * @param amountToAdd the amount to add, measured in terms of the unit, positive or negative 687 * @param unit the unit that the amount is measured in, must have an exact duration, not null 688 * @return a {@code Duration} based on this duration with the specified duration added, not null 689 * @throws UnsupportedTemporalTypeException if the unit is not supported 690 * @throws ArithmeticException if numeric overflow occurs 691 */ plus(long amountToAdd, TemporalUnit unit)692 public Duration plus(long amountToAdd, TemporalUnit unit) { 693 Objects.requireNonNull(unit, "unit"); 694 if (unit == DAYS) { 695 return plus(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY), 0); 696 } 697 if (unit.isDurationEstimated()) { 698 throw new UnsupportedTemporalTypeException("Unit must not have an estimated duration"); 699 } 700 if (amountToAdd == 0) { 701 return this; 702 } 703 if (unit instanceof ChronoUnit chronoUnit) { 704 switch (chronoUnit) { 705 case NANOS: return plusNanos(amountToAdd); 706 case MICROS: return plusSeconds((amountToAdd / (1000_000L * 1000)) * 1000).plusNanos((amountToAdd % (1000_000L * 1000)) * 1000); 707 case MILLIS: return plusMillis(amountToAdd); 708 case SECONDS: return plusSeconds(amountToAdd); 709 } 710 return plusSeconds(Math.multiplyExact(unit.getDuration().seconds, amountToAdd)); 711 } 712 Duration duration = unit.getDuration().multipliedBy(amountToAdd); 713 return plusSeconds(duration.getSeconds()).plusNanos(duration.getNano()); 714 } 715 716 //----------------------------------------------------------------------- 717 /** 718 * Returns a copy of this duration with the specified duration in standard 24 hour days added. 719 * <p> 720 * The number of days is multiplied by 86400 to obtain the number of seconds to add. 721 * This is based on the standard definition of a day as 24 hours. 722 * <p> 723 * This instance is immutable and unaffected by this method call. 724 * 725 * @param daysToAdd the days to add, positive or negative 726 * @return a {@code Duration} based on this duration with the specified days added, not null 727 * @throws ArithmeticException if numeric overflow occurs 728 */ plusDays(long daysToAdd)729 public Duration plusDays(long daysToAdd) { 730 return plus(Math.multiplyExact(daysToAdd, SECONDS_PER_DAY), 0); 731 } 732 733 /** 734 * Returns a copy of this duration with the specified duration in hours added. 735 * <p> 736 * This instance is immutable and unaffected by this method call. 737 * 738 * @param hoursToAdd the hours to add, positive or negative 739 * @return a {@code Duration} based on this duration with the specified hours added, not null 740 * @throws ArithmeticException if numeric overflow occurs 741 */ plusHours(long hoursToAdd)742 public Duration plusHours(long hoursToAdd) { 743 return plus(Math.multiplyExact(hoursToAdd, SECONDS_PER_HOUR), 0); 744 } 745 746 /** 747 * Returns a copy of this duration with the specified duration in minutes added. 748 * <p> 749 * This instance is immutable and unaffected by this method call. 750 * 751 * @param minutesToAdd the minutes to add, positive or negative 752 * @return a {@code Duration} based on this duration with the specified minutes added, not null 753 * @throws ArithmeticException if numeric overflow occurs 754 */ plusMinutes(long minutesToAdd)755 public Duration plusMinutes(long minutesToAdd) { 756 return plus(Math.multiplyExact(minutesToAdd, SECONDS_PER_MINUTE), 0); 757 } 758 759 /** 760 * Returns a copy of this duration with the specified duration in seconds added. 761 * <p> 762 * This instance is immutable and unaffected by this method call. 763 * 764 * @param secondsToAdd the seconds to add, positive or negative 765 * @return a {@code Duration} based on this duration with the specified seconds added, not null 766 * @throws ArithmeticException if numeric overflow occurs 767 */ plusSeconds(long secondsToAdd)768 public Duration plusSeconds(long secondsToAdd) { 769 return plus(secondsToAdd, 0); 770 } 771 772 /** 773 * Returns a copy of this duration with the specified duration in milliseconds added. 774 * <p> 775 * This instance is immutable and unaffected by this method call. 776 * 777 * @param millisToAdd the milliseconds to add, positive or negative 778 * @return a {@code Duration} based on this duration with the specified milliseconds added, not null 779 * @throws ArithmeticException if numeric overflow occurs 780 */ plusMillis(long millisToAdd)781 public Duration plusMillis(long millisToAdd) { 782 return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000); 783 } 784 785 /** 786 * Returns a copy of this duration with the specified duration in nanoseconds added. 787 * <p> 788 * This instance is immutable and unaffected by this method call. 789 * 790 * @param nanosToAdd the nanoseconds to add, positive or negative 791 * @return a {@code Duration} based on this duration with the specified nanoseconds added, not null 792 * @throws ArithmeticException if numeric overflow occurs 793 */ plusNanos(long nanosToAdd)794 public Duration plusNanos(long nanosToAdd) { 795 return plus(0, nanosToAdd); 796 } 797 798 /** 799 * Returns a copy of this duration with the specified duration added. 800 * <p> 801 * This instance is immutable and unaffected by this method call. 802 * 803 * @param secondsToAdd the seconds to add, positive or negative 804 * @param nanosToAdd the nanos to add, positive or negative 805 * @return a {@code Duration} based on this duration with the specified seconds added, not null 806 * @throws ArithmeticException if numeric overflow occurs 807 */ plus(long secondsToAdd, long nanosToAdd)808 private Duration plus(long secondsToAdd, long nanosToAdd) { 809 if ((secondsToAdd | nanosToAdd) == 0) { 810 return this; 811 } 812 long epochSec = Math.addExact(seconds, secondsToAdd); 813 epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND); 814 nanosToAdd = nanosToAdd % NANOS_PER_SECOND; 815 long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND 816 return ofSeconds(epochSec, nanoAdjustment); 817 } 818 819 //----------------------------------------------------------------------- 820 /** 821 * Returns a copy of this duration with the specified duration subtracted. 822 * <p> 823 * This instance is immutable and unaffected by this method call. 824 * 825 * @param duration the duration to subtract, positive or negative, not null 826 * @return a {@code Duration} based on this duration with the specified duration subtracted, not null 827 * @throws ArithmeticException if numeric overflow occurs 828 */ minus(Duration duration)829 public Duration minus(Duration duration) { 830 long secsToSubtract = duration.getSeconds(); 831 int nanosToSubtract = duration.getNano(); 832 if (secsToSubtract == Long.MIN_VALUE) { 833 return plus(Long.MAX_VALUE, -nanosToSubtract).plus(1, 0); 834 } 835 return plus(-secsToSubtract, -nanosToSubtract); 836 } 837 838 /** 839 * Returns a copy of this duration with the specified duration subtracted. 840 * <p> 841 * The duration amount is measured in terms of the specified unit. 842 * Only a subset of units are accepted by this method. 843 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or 844 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception. 845 * <p> 846 * This instance is immutable and unaffected by this method call. 847 * 848 * @param amountToSubtract the amount to subtract, measured in terms of the unit, positive or negative 849 * @param unit the unit that the amount is measured in, must have an exact duration, not null 850 * @return a {@code Duration} based on this duration with the specified duration subtracted, not null 851 * @throws ArithmeticException if numeric overflow occurs 852 */ minus(long amountToSubtract, TemporalUnit unit)853 public Duration minus(long amountToSubtract, TemporalUnit unit) { 854 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); 855 } 856 857 //----------------------------------------------------------------------- 858 /** 859 * Returns a copy of this duration with the specified duration in standard 24 hour days subtracted. 860 * <p> 861 * The number of days is multiplied by 86400 to obtain the number of seconds to subtract. 862 * This is based on the standard definition of a day as 24 hours. 863 * <p> 864 * This instance is immutable and unaffected by this method call. 865 * 866 * @param daysToSubtract the days to subtract, positive or negative 867 * @return a {@code Duration} based on this duration with the specified days subtracted, not null 868 * @throws ArithmeticException if numeric overflow occurs 869 */ minusDays(long daysToSubtract)870 public Duration minusDays(long daysToSubtract) { 871 return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract)); 872 } 873 874 /** 875 * Returns a copy of this duration with the specified duration in hours subtracted. 876 * <p> 877 * The number of hours is multiplied by 3600 to obtain the number of seconds to subtract. 878 * <p> 879 * This instance is immutable and unaffected by this method call. 880 * 881 * @param hoursToSubtract the hours to subtract, positive or negative 882 * @return a {@code Duration} based on this duration with the specified hours subtracted, not null 883 * @throws ArithmeticException if numeric overflow occurs 884 */ minusHours(long hoursToSubtract)885 public Duration minusHours(long hoursToSubtract) { 886 return (hoursToSubtract == Long.MIN_VALUE ? plusHours(Long.MAX_VALUE).plusHours(1) : plusHours(-hoursToSubtract)); 887 } 888 889 /** 890 * Returns a copy of this duration with the specified duration in minutes subtracted. 891 * <p> 892 * The number of hours is multiplied by 60 to obtain the number of seconds to subtract. 893 * <p> 894 * This instance is immutable and unaffected by this method call. 895 * 896 * @param minutesToSubtract the minutes to subtract, positive or negative 897 * @return a {@code Duration} based on this duration with the specified minutes subtracted, not null 898 * @throws ArithmeticException if numeric overflow occurs 899 */ minusMinutes(long minutesToSubtract)900 public Duration minusMinutes(long minutesToSubtract) { 901 return (minutesToSubtract == Long.MIN_VALUE ? plusMinutes(Long.MAX_VALUE).plusMinutes(1) : plusMinutes(-minutesToSubtract)); 902 } 903 904 /** 905 * Returns a copy of this duration with the specified duration in seconds subtracted. 906 * <p> 907 * This instance is immutable and unaffected by this method call. 908 * 909 * @param secondsToSubtract the seconds to subtract, positive or negative 910 * @return a {@code Duration} based on this duration with the specified seconds subtracted, not null 911 * @throws ArithmeticException if numeric overflow occurs 912 */ minusSeconds(long secondsToSubtract)913 public Duration minusSeconds(long secondsToSubtract) { 914 return (secondsToSubtract == Long.MIN_VALUE ? plusSeconds(Long.MAX_VALUE).plusSeconds(1) : plusSeconds(-secondsToSubtract)); 915 } 916 917 /** 918 * Returns a copy of this duration with the specified duration in milliseconds subtracted. 919 * <p> 920 * This instance is immutable and unaffected by this method call. 921 * 922 * @param millisToSubtract the milliseconds to subtract, positive or negative 923 * @return a {@code Duration} based on this duration with the specified milliseconds subtracted, not null 924 * @throws ArithmeticException if numeric overflow occurs 925 */ minusMillis(long millisToSubtract)926 public Duration minusMillis(long millisToSubtract) { 927 return (millisToSubtract == Long.MIN_VALUE ? plusMillis(Long.MAX_VALUE).plusMillis(1) : plusMillis(-millisToSubtract)); 928 } 929 930 /** 931 * Returns a copy of this duration with the specified duration in nanoseconds subtracted. 932 * <p> 933 * This instance is immutable and unaffected by this method call. 934 * 935 * @param nanosToSubtract the nanoseconds to subtract, positive or negative 936 * @return a {@code Duration} based on this duration with the specified nanoseconds subtracted, not null 937 * @throws ArithmeticException if numeric overflow occurs 938 */ minusNanos(long nanosToSubtract)939 public Duration minusNanos(long nanosToSubtract) { 940 return (nanosToSubtract == Long.MIN_VALUE ? plusNanos(Long.MAX_VALUE).plusNanos(1) : plusNanos(-nanosToSubtract)); 941 } 942 943 //----------------------------------------------------------------------- 944 /** 945 * Returns a copy of this duration multiplied by the scalar. 946 * <p> 947 * This instance is immutable and unaffected by this method call. 948 * 949 * @param multiplicand the value to multiply the duration by, positive or negative 950 * @return a {@code Duration} based on this duration multiplied by the specified scalar, not null 951 * @throws ArithmeticException if numeric overflow occurs 952 */ multipliedBy(long multiplicand)953 public Duration multipliedBy(long multiplicand) { 954 if (multiplicand == 0) { 955 return ZERO; 956 } 957 if (multiplicand == 1) { 958 return this; 959 } 960 return create(toBigDecimalSeconds().multiply(BigDecimal.valueOf(multiplicand))); 961 } 962 963 /** 964 * Returns a copy of this duration divided by the specified value. 965 * <p> 966 * This instance is immutable and unaffected by this method call. 967 * 968 * @param divisor the value to divide the duration by, positive or negative, not zero 969 * @return a {@code Duration} based on this duration divided by the specified divisor, not null 970 * @throws ArithmeticException if the divisor is zero or if numeric overflow occurs 971 */ dividedBy(long divisor)972 public Duration dividedBy(long divisor) { 973 if (divisor == 0) { 974 throw new ArithmeticException("Cannot divide by zero"); 975 } 976 if (divisor == 1) { 977 return this; 978 } 979 return create(toBigDecimalSeconds().divide(BigDecimal.valueOf(divisor), RoundingMode.DOWN)); 980 } 981 982 /** 983 * Returns number of whole times a specified Duration occurs within this Duration. 984 * <p> 985 * This instance is immutable and unaffected by this method call. 986 * 987 * @param divisor the value to divide the duration by, positive or negative, not null 988 * @return number of whole times, rounded toward zero, a specified 989 * {@code Duration} occurs within this Duration, may be negative 990 * @throws ArithmeticException if the divisor is zero, or if numeric overflow occurs 991 * @since 9 992 */ dividedBy(Duration divisor)993 public long dividedBy(Duration divisor) { 994 Objects.requireNonNull(divisor, "divisor"); 995 BigDecimal dividendBigD = toBigDecimalSeconds(); 996 BigDecimal divisorBigD = divisor.toBigDecimalSeconds(); 997 return dividendBigD.divideToIntegralValue(divisorBigD).longValueExact(); 998 } 999 1000 /** 1001 * Converts this duration to the total length in seconds and 1002 * fractional nanoseconds expressed as a {@code BigDecimal}. 1003 * 1004 * @return the total length of the duration in seconds, with a scale of 9, not null 1005 */ toBigDecimalSeconds()1006 private BigDecimal toBigDecimalSeconds() { 1007 return BigDecimal.valueOf(seconds).add(BigDecimal.valueOf(nanos, 9)); 1008 } 1009 1010 /** 1011 * Creates an instance of {@code Duration} from a number of seconds. 1012 * 1013 * @param seconds the number of seconds, up to scale 9, positive or negative 1014 * @return a {@code Duration}, not null 1015 * @throws ArithmeticException if numeric overflow occurs 1016 */ create(BigDecimal seconds)1017 private static Duration create(BigDecimal seconds) { 1018 BigInteger nanos = seconds.movePointRight(9).toBigIntegerExact(); 1019 BigInteger[] divRem = nanos.divideAndRemainder(BI_NANOS_PER_SECOND); 1020 if (divRem[0].bitLength() > 63) { 1021 throw new ArithmeticException("Exceeds capacity of Duration: " + nanos); 1022 } 1023 return ofSeconds(divRem[0].longValue(), divRem[1].intValue()); 1024 } 1025 1026 //----------------------------------------------------------------------- 1027 /** 1028 * Returns a copy of this duration with the length negated. 1029 * <p> 1030 * This method swaps the sign of the total length of this duration. 1031 * For example, {@code PT1.3S} will be returned as {@code PT-1.3S}. 1032 * <p> 1033 * This instance is immutable and unaffected by this method call. 1034 * 1035 * @return a {@code Duration} based on this duration with the amount negated, not null 1036 * @throws ArithmeticException if numeric overflow occurs 1037 */ negated()1038 public Duration negated() { 1039 return multipliedBy(-1); 1040 } 1041 1042 /** 1043 * Returns a copy of this duration with a positive length. 1044 * <p> 1045 * This method returns a positive duration by effectively removing the sign from any negative total length. 1046 * For example, {@code PT-1.3S} will be returned as {@code PT1.3S}. 1047 * <p> 1048 * This instance is immutable and unaffected by this method call. 1049 * 1050 * @return a {@code Duration} based on this duration with an absolute length, not null 1051 * @throws ArithmeticException if numeric overflow occurs 1052 */ abs()1053 public Duration abs() { 1054 return isNegative() ? negated() : this; 1055 } 1056 1057 //------------------------------------------------------------------------- 1058 /** 1059 * Adds this duration to the specified temporal object. 1060 * <p> 1061 * This returns a temporal object of the same observable type as the input 1062 * with this duration added. 1063 * <p> 1064 * In most cases, it is clearer to reverse the calling pattern by using 1065 * {@link Temporal#plus(TemporalAmount)}. 1066 * <pre> 1067 * // these two lines are equivalent, but the second approach is recommended 1068 * dateTime = thisDuration.addTo(dateTime); 1069 * dateTime = dateTime.plus(thisDuration); 1070 * </pre> 1071 * <p> 1072 * The calculation will add the seconds, then nanos. 1073 * Only non-zero amounts will be added. 1074 * <p> 1075 * This instance is immutable and unaffected by this method call. 1076 * 1077 * @param temporal the temporal object to adjust, not null 1078 * @return an object of the same type with the adjustment made, not null 1079 * @throws DateTimeException if unable to add 1080 * @throws ArithmeticException if numeric overflow occurs 1081 */ 1082 @Override addTo(Temporal temporal)1083 public Temporal addTo(Temporal temporal) { 1084 if (seconds != 0) { 1085 temporal = temporal.plus(seconds, SECONDS); 1086 } 1087 if (nanos != 0) { 1088 temporal = temporal.plus(nanos, NANOS); 1089 } 1090 return temporal; 1091 } 1092 1093 /** 1094 * Subtracts this duration from the specified temporal object. 1095 * <p> 1096 * This returns a temporal object of the same observable type as the input 1097 * with this duration subtracted. 1098 * <p> 1099 * In most cases, it is clearer to reverse the calling pattern by using 1100 * {@link Temporal#minus(TemporalAmount)}. 1101 * <pre> 1102 * // these two lines are equivalent, but the second approach is recommended 1103 * dateTime = thisDuration.subtractFrom(dateTime); 1104 * dateTime = dateTime.minus(thisDuration); 1105 * </pre> 1106 * <p> 1107 * The calculation will subtract the seconds, then nanos. 1108 * Only non-zero amounts will be added. 1109 * <p> 1110 * This instance is immutable and unaffected by this method call. 1111 * 1112 * @param temporal the temporal object to adjust, not null 1113 * @return an object of the same type with the adjustment made, not null 1114 * @throws DateTimeException if unable to subtract 1115 * @throws ArithmeticException if numeric overflow occurs 1116 */ 1117 @Override subtractFrom(Temporal temporal)1118 public Temporal subtractFrom(Temporal temporal) { 1119 if (seconds != 0) { 1120 temporal = temporal.minus(seconds, SECONDS); 1121 } 1122 if (nanos != 0) { 1123 temporal = temporal.minus(nanos, NANOS); 1124 } 1125 return temporal; 1126 } 1127 1128 //----------------------------------------------------------------------- 1129 /** 1130 * Gets the number of days in this duration. 1131 * <p> 1132 * This returns the total number of days in the duration by dividing the 1133 * number of seconds by 86400. 1134 * This is based on the standard definition of a day as 24 hours. 1135 * <p> 1136 * This instance is immutable and unaffected by this method call. 1137 * 1138 * @return the number of days in the duration, may be negative 1139 */ toDays()1140 public long toDays() { 1141 return seconds / SECONDS_PER_DAY; 1142 } 1143 1144 /** 1145 * Gets the number of hours in this duration. 1146 * <p> 1147 * This returns the total number of hours in the duration by dividing the 1148 * number of seconds by 3600. 1149 * <p> 1150 * This instance is immutable and unaffected by this method call. 1151 * 1152 * @return the number of hours in the duration, may be negative 1153 */ toHours()1154 public long toHours() { 1155 return seconds / SECONDS_PER_HOUR; 1156 } 1157 1158 /** 1159 * Gets the number of minutes in this duration. 1160 * <p> 1161 * This returns the total number of minutes in the duration by dividing the 1162 * number of seconds by 60. 1163 * <p> 1164 * This instance is immutable and unaffected by this method call. 1165 * 1166 * @return the number of minutes in the duration, may be negative 1167 */ toMinutes()1168 public long toMinutes() { 1169 return seconds / SECONDS_PER_MINUTE; 1170 } 1171 1172 /** 1173 * Gets the number of seconds in this duration. 1174 * <p> 1175 * This returns the total number of whole seconds in the duration. 1176 * <p> 1177 * This instance is immutable and unaffected by this method call. 1178 * 1179 * @return the whole seconds part of the length of the duration, positive or negative 1180 * @since 9 1181 */ toSeconds()1182 public long toSeconds() { 1183 return seconds; 1184 } 1185 1186 /** 1187 * Converts this duration to the total length in milliseconds. 1188 * <p> 1189 * If this duration is too large to fit in a {@code long} milliseconds, then an 1190 * exception is thrown. 1191 * <p> 1192 * If this duration has greater than millisecond precision, then the conversion 1193 * will drop any excess precision information as though the amount in nanoseconds 1194 * was subject to integer division by one million. 1195 * 1196 * @return the total length of the duration in milliseconds 1197 * @throws ArithmeticException if numeric overflow occurs 1198 */ toMillis()1199 public long toMillis() { 1200 long millis = Math.multiplyExact(seconds, 1000); 1201 millis = Math.addExact(millis, nanos / 1000_000); 1202 return millis; 1203 } 1204 1205 /** 1206 * Converts this duration to the total length in nanoseconds expressed as a {@code long}. 1207 * <p> 1208 * If this duration is too large to fit in a {@code long} nanoseconds, then an 1209 * exception is thrown. 1210 * 1211 * @return the total length of the duration in nanoseconds 1212 * @throws ArithmeticException if numeric overflow occurs 1213 */ toNanos()1214 public long toNanos() { 1215 long totalNanos = Math.multiplyExact(seconds, NANOS_PER_SECOND); 1216 totalNanos = Math.addExact(totalNanos, nanos); 1217 return totalNanos; 1218 } 1219 1220 /** 1221 * Extracts the number of days in the duration. 1222 * <p> 1223 * This returns the total number of days in the duration by dividing the 1224 * number of seconds by 86400. 1225 * This is based on the standard definition of a day as 24 hours. 1226 * <p> 1227 * This instance is immutable and unaffected by this method call. 1228 * 1229 * @return the number of days in the duration, may be negative 1230 * @since 9 1231 */ toDaysPart()1232 public long toDaysPart(){ 1233 return seconds / SECONDS_PER_DAY; 1234 } 1235 1236 /** 1237 * Extracts the number of hours part in the duration. 1238 * <p> 1239 * This returns the number of remaining hours when dividing {@link #toHours} 1240 * by hours in a day. 1241 * This is based on the standard definition of a day as 24 hours. 1242 * <p> 1243 * This instance is immutable and unaffected by this method call. 1244 * 1245 * @return the number of hours part in the duration, may be negative 1246 * @since 9 1247 */ toHoursPart()1248 public int toHoursPart(){ 1249 return (int) (toHours() % 24); 1250 } 1251 1252 /** 1253 * Extracts the number of minutes part in the duration. 1254 * <p> 1255 * This returns the number of remaining minutes when dividing {@link #toMinutes} 1256 * by minutes in an hour. 1257 * This is based on the standard definition of an hour as 60 minutes. 1258 * <p> 1259 * This instance is immutable and unaffected by this method call. 1260 * 1261 * @return the number of minutes parts in the duration, may be negative 1262 * @since 9 1263 */ toMinutesPart()1264 public int toMinutesPart(){ 1265 return (int) (toMinutes() % MINUTES_PER_HOUR); 1266 } 1267 1268 /** 1269 * Extracts the number of seconds part in the duration. 1270 * <p> 1271 * This returns the remaining seconds when dividing {@link #toSeconds} 1272 * by seconds in a minute. 1273 * This is based on the standard definition of a minute as 60 seconds. 1274 * <p> 1275 * This instance is immutable and unaffected by this method call. 1276 * 1277 * @return the number of seconds parts in the duration, may be negative 1278 * @since 9 1279 */ toSecondsPart()1280 public int toSecondsPart(){ 1281 return (int) (seconds % SECONDS_PER_MINUTE); 1282 } 1283 1284 /** 1285 * Extracts the number of milliseconds part of the duration. 1286 * <p> 1287 * This returns the milliseconds part by dividing the number of nanoseconds by 1,000,000. 1288 * The length of the duration is stored using two fields - seconds and nanoseconds. 1289 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to 1290 * the length in seconds. 1291 * The total duration is defined by calling {@link #getNano()} and {@link #getSeconds()}. 1292 * <p> 1293 * This instance is immutable and unaffected by this method call. 1294 * 1295 * @return the number of milliseconds part of the duration. 1296 * @since 9 1297 */ toMillisPart()1298 public int toMillisPart(){ 1299 return nanos / 1000_000; 1300 } 1301 1302 /** 1303 * Get the nanoseconds part within seconds of the duration. 1304 * <p> 1305 * The length of the duration is stored using two fields - seconds and nanoseconds. 1306 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to 1307 * the length in seconds. 1308 * The total duration is defined by calling {@link #getNano()} and {@link #getSeconds()}. 1309 * <p> 1310 * This instance is immutable and unaffected by this method call. 1311 * 1312 * @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999 1313 * @since 9 1314 */ toNanosPart()1315 public int toNanosPart(){ 1316 return nanos; 1317 } 1318 1319 1320 //----------------------------------------------------------------------- 1321 /** 1322 * Returns a copy of this {@code Duration} truncated to the specified unit. 1323 * <p> 1324 * Truncating the duration returns a copy of the original with conceptual fields 1325 * smaller than the specified unit set to zero. 1326 * For example, truncating with the {@link ChronoUnit#MINUTES MINUTES} unit will 1327 * round down towards zero to the nearest minute, setting the seconds and 1328 * nanoseconds to zero. 1329 * <p> 1330 * The unit must have a {@linkplain TemporalUnit#getDuration() duration} 1331 * that divides into the length of a standard day without remainder. 1332 * This includes all 1333 * {@linkplain ChronoUnit#isTimeBased() time-based units on {@code ChronoUnit}} 1334 * and {@link ChronoUnit#DAYS DAYS}. Other ChronoUnits throw an exception. 1335 * <p> 1336 * This instance is immutable and unaffected by this method call. 1337 * 1338 * @param unit the unit to truncate to, not null 1339 * @return a {@code Duration} based on this duration with the time truncated, not null 1340 * @throws DateTimeException if the unit is invalid for truncation 1341 * @throws UnsupportedTemporalTypeException if the unit is not supported 1342 * @since 9 1343 */ truncatedTo(TemporalUnit unit)1344 public Duration truncatedTo(TemporalUnit unit) { 1345 Objects.requireNonNull(unit, "unit"); 1346 if (unit == ChronoUnit.SECONDS && (seconds >= 0 || nanos == 0)) { 1347 return new Duration(seconds, 0); 1348 } else if (unit == ChronoUnit.NANOS) { 1349 return this; 1350 } 1351 Duration unitDur = unit.getDuration(); 1352 if (unitDur.getSeconds() > LocalTime.SECONDS_PER_DAY) { 1353 throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation"); 1354 } 1355 long dur = unitDur.toNanos(); 1356 if ((LocalTime.NANOS_PER_DAY % dur) != 0) { 1357 throw new UnsupportedTemporalTypeException("Unit must divide into a standard day without remainder"); 1358 } 1359 long nod = (seconds % LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + nanos; 1360 long result = (nod / dur) * dur; 1361 return plusNanos(result - nod); 1362 } 1363 1364 //----------------------------------------------------------------------- 1365 /** 1366 * Compares this duration to the specified {@code Duration}. 1367 * <p> 1368 * The comparison is based on the total length of the durations. 1369 * It is "consistent with equals", as defined by {@link Comparable}. 1370 * 1371 * @param otherDuration the other duration to compare to, not null 1372 * @return the comparator value, negative if less, positive if greater 1373 */ 1374 @Override compareTo(Duration otherDuration)1375 public int compareTo(Duration otherDuration) { 1376 int cmp = Long.compare(seconds, otherDuration.seconds); 1377 if (cmp != 0) { 1378 return cmp; 1379 } 1380 return nanos - otherDuration.nanos; 1381 } 1382 1383 //----------------------------------------------------------------------- 1384 /** 1385 * Checks if this duration is equal to the specified {@code Duration}. 1386 * <p> 1387 * The comparison is based on the total length of the durations. 1388 * 1389 * @param other the other duration, null returns false 1390 * @return true if the other duration is equal to this one 1391 */ 1392 @Override equals(Object other)1393 public boolean equals(Object other) { 1394 if (this == other) { 1395 return true; 1396 } 1397 return (other instanceof Duration otherDuration) 1398 && this.seconds == otherDuration.seconds 1399 && this.nanos == otherDuration.nanos; 1400 } 1401 1402 /** 1403 * A hash code for this duration. 1404 * 1405 * @return a suitable hash code 1406 */ 1407 @Override hashCode()1408 public int hashCode() { 1409 return ((int) (seconds ^ (seconds >>> 32))) + (51 * nanos); 1410 } 1411 1412 //----------------------------------------------------------------------- 1413 /** 1414 * A string representation of this duration using ISO-8601 seconds 1415 * based representation, such as {@code PT8H6M12.345S}. 1416 * <p> 1417 * The format of the returned string will be {@code PTnHnMnS}, where n is 1418 * the relevant hours, minutes or seconds part of the duration. 1419 * Any fractional seconds are placed after a decimal point in the seconds section. 1420 * If a section has a zero value, it is omitted. 1421 * The hours, minutes and seconds will all have the same sign. 1422 * <p> 1423 * Examples: 1424 * <pre> 1425 * "20.345 seconds" -- "PT20.345S 1426 * "15 minutes" (15 * 60 seconds) -- "PT15M" 1427 * "10 hours" (10 * 3600 seconds) -- "PT10H" 1428 * "2 days" (2 * 86400 seconds) -- "PT48H" 1429 * </pre> 1430 * Note that multiples of 24 hours are not output as days to avoid confusion 1431 * with {@code Period}. 1432 * 1433 * @return an ISO-8601 representation of this duration, not null 1434 */ 1435 @Override toString()1436 public String toString() { 1437 if (this == ZERO) { 1438 return "PT0S"; 1439 } 1440 long hours = seconds / SECONDS_PER_HOUR; 1441 int minutes = (int) ((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE); 1442 int secs = (int) (seconds % SECONDS_PER_MINUTE); 1443 StringBuilder buf = new StringBuilder(24); 1444 buf.append("PT"); 1445 if (hours != 0) { 1446 buf.append(hours).append('H'); 1447 } 1448 if (minutes != 0) { 1449 buf.append(minutes).append('M'); 1450 } 1451 if (secs == 0 && nanos == 0 && buf.length() > 2) { 1452 return buf.toString(); 1453 } 1454 if (secs < 0 && nanos > 0) { 1455 if (secs == -1) { 1456 buf.append("-0"); 1457 } else { 1458 buf.append(secs + 1); 1459 } 1460 } else { 1461 buf.append(secs); 1462 } 1463 if (nanos > 0) { 1464 int pos = buf.length(); 1465 if (secs < 0) { 1466 buf.append(2 * NANOS_PER_SECOND - nanos); 1467 } else { 1468 buf.append(nanos + NANOS_PER_SECOND); 1469 } 1470 while (buf.charAt(buf.length() - 1) == '0') { 1471 buf.setLength(buf.length() - 1); 1472 } 1473 buf.setCharAt(pos, '.'); 1474 } 1475 buf.append('S'); 1476 return buf.toString(); 1477 } 1478 1479 //----------------------------------------------------------------------- 1480 /** 1481 * Writes the object using a 1482 * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>. 1483 * @serialData 1484 * <pre> 1485 * out.writeByte(1); // identifies a Duration 1486 * out.writeLong(seconds); 1487 * out.writeInt(nanos); 1488 * </pre> 1489 * 1490 * @return the instance of {@code Ser}, not null 1491 */ 1492 @java.io.Serial writeReplace()1493 private Object writeReplace() { 1494 return new Ser(Ser.DURATION_TYPE, this); 1495 } 1496 1497 /** 1498 * Defend against malicious streams. 1499 * 1500 * @param s the stream to read 1501 * @throws InvalidObjectException always 1502 */ 1503 @java.io.Serial readObject(ObjectInputStream s)1504 private void readObject(ObjectInputStream s) throws InvalidObjectException { 1505 throw new InvalidObjectException("Deserialization via serialization delegate"); 1506 } 1507 writeExternal(DataOutput out)1508 void writeExternal(DataOutput out) throws IOException { 1509 out.writeLong(seconds); 1510 out.writeInt(nanos); 1511 } 1512 readExternal(DataInput in)1513 static Duration readExternal(DataInput in) throws IOException { 1514 long seconds = in.readLong(); 1515 int nanos = in.readInt(); 1516 return Duration.ofSeconds(seconds, nanos); 1517 } 1518 1519 } 1520