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