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 ("T".equals(matcher.group(3)) == false) { 392 boolean negate = "-".equals(matcher.group(1)); 393 String dayMatch = matcher.group(2); 394 String hourMatch = matcher.group(4); 395 String minuteMatch = matcher.group(5); 396 String secondMatch = matcher.group(6); 397 String fractionMatch = matcher.group(7); 398 if (dayMatch != null || hourMatch != null || minuteMatch != null || secondMatch != null) { 399 long daysAsSecs = parseNumber(text, dayMatch, SECONDS_PER_DAY, "days"); 400 long hoursAsSecs = parseNumber(text, hourMatch, SECONDS_PER_HOUR, "hours"); 401 long minsAsSecs = parseNumber(text, minuteMatch, SECONDS_PER_MINUTE, "minutes"); 402 long seconds = parseNumber(text, secondMatch, 1, "seconds"); 403 int nanos = parseFraction(text, fractionMatch, seconds < 0 ? -1 : 1); 404 try { 405 return create(negate, daysAsSecs, hoursAsSecs, minsAsSecs, seconds, nanos); 406 } catch (ArithmeticException ex) { 407 throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: overflow", text, 0).initCause(ex); 408 } 409 } 410 } 411 } 412 throw new DateTimeParseException("Text cannot be parsed to a Duration", text, 0); 413 } 414 415 private static long parseNumber(CharSequence text, String parsed, int multiplier, String errorText) { 416 // regex limits to [-+]?[0-9]+ 417 if (parsed == null) { 418 return 0; 419 } 420 try { 421 long val = Long.parseLong(parsed); 422 return Math.multiplyExact(val, multiplier); 423 } catch (NumberFormatException | ArithmeticException ex) { 424 throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: " + errorText, text, 0).initCause(ex); 425 } 426 } 427 428 private static int parseFraction(CharSequence text, String parsed, int negate) { 429 // regex limits to [0-9]{0,9} 430 if (parsed == null || parsed.length() == 0) { 431 return 0; 432 } 433 try { 434 parsed = (parsed + "000000000").substring(0, 9); 435 return Integer.parseInt(parsed) * negate; 436 } catch (NumberFormatException | ArithmeticException ex) { 437 throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: fraction", text, 0).initCause(ex); 438 } 439 } 440 441 private static Duration create(boolean negate, long daysAsSecs, long hoursAsSecs, long minsAsSecs, long secs, int nanos) { 442 long seconds = Math.addExact(daysAsSecs, Math.addExact(hoursAsSecs, Math.addExact(minsAsSecs, secs))); 443 if (negate) { 444 return ofSeconds(seconds, nanos).negated(); 445 } 446 return ofSeconds(seconds, nanos); 447 } 448 449 //----------------------------------------------------------------------- 450 /** 451 * Obtains a {@code Duration} representing the duration between two temporal objects. 452 * <p> 453 * This calculates the duration between two temporal objects. If the objects 454 * are of different types, then the duration is calculated based on the type 455 * of the first object. For example, if the first argument is a {@code LocalTime} 456 * then the second argument is converted to a {@code LocalTime}. 457 * <p> 458 * The specified temporal objects must support the {@link ChronoUnit#SECONDS SECONDS} unit. 459 * For full accuracy, either the {@link ChronoUnit#NANOS NANOS} unit or the 460 * {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} field should be supported. 461 * <p> 462 * The result of this method can be a negative period if the end is before the start. 463 * To guarantee to obtain a positive duration call {@link #abs()} on the result. 464 * 465 * @param startInclusive the start instant, inclusive, not null 466 * @param endExclusive the end instant, exclusive, not null 467 * @return a {@code Duration}, not null 468 * @throws DateTimeException if the seconds between the temporals cannot be obtained 469 * @throws ArithmeticException if the calculation exceeds the capacity of {@code Duration} 470 */ 471 public static Duration between(Temporal startInclusive, Temporal endExclusive) { 472 try { 473 return ofNanos(startInclusive.until(endExclusive, NANOS)); 474 } catch (DateTimeException | ArithmeticException ex) { 475 long secs = startInclusive.until(endExclusive, SECONDS); 476 long nanos; 477 try { 478 nanos = endExclusive.getLong(NANO_OF_SECOND) - startInclusive.getLong(NANO_OF_SECOND); 479 if (secs > 0 && nanos < 0) { 480 secs++; 481 } else if (secs < 0 && nanos > 0) { 482 secs--; 483 } 484 } catch (DateTimeException ex2) { 485 nanos = 0; 486 } 487 return ofSeconds(secs, nanos); 488 } 489 } 490 491 //----------------------------------------------------------------------- 492 /** 493 * Obtains an instance of {@code Duration} using seconds and nanoseconds. 494 * 495 * @param seconds the length of the duration in seconds, positive or negative 496 * @param nanoAdjustment the nanosecond adjustment within the second, from 0 to 999,999,999 497 */ 498 private static Duration create(long seconds, int nanoAdjustment) { 499 if ((seconds | nanoAdjustment) == 0) { 500 return ZERO; 501 } 502 return new Duration(seconds, nanoAdjustment); 503 } 504 505 /** 506 * Constructs an instance of {@code Duration} using seconds and nanoseconds. 507 * 508 * @param seconds the length of the duration in seconds, positive or negative 509 * @param nanos the nanoseconds within the second, from 0 to 999,999,999 510 */ 511 private Duration(long seconds, int nanos) { 512 super(); 513 this.seconds = seconds; 514 this.nanos = nanos; 515 } 516 517 //----------------------------------------------------------------------- 518 /** 519 * Gets the value of the requested unit. 520 * <p> 521 * This returns a value for each of the two supported units, 522 * {@link ChronoUnit#SECONDS SECONDS} and {@link ChronoUnit#NANOS NANOS}. 523 * All other units throw an exception. 524 * 525 * @param unit the {@code TemporalUnit} for which to return the value 526 * @return the long value of the unit 527 * @throws DateTimeException if the unit is not supported 528 * @throws UnsupportedTemporalTypeException if the unit is not supported 529 */ 530 @Override 531 public long get(TemporalUnit unit) { 532 if (unit == SECONDS) { 533 return seconds; 534 } else if (unit == NANOS) { 535 return nanos; 536 } else { 537 throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); 538 } 539 } 540 541 /** 542 * Gets the set of units supported by this duration. 543 * <p> 544 * The supported units are {@link ChronoUnit#SECONDS SECONDS}, 545 * and {@link ChronoUnit#NANOS NANOS}. 546 * They are returned in the order seconds, nanos. 547 * <p> 548 * This set can be used in conjunction with {@link #get(TemporalUnit)} 549 * to access the entire state of the duration. 550 * 551 * @return a list containing the seconds and nanos units, not null 552 */ 553 @Override 554 public List<TemporalUnit> getUnits() { 555 return DurationUnits.UNITS; 556 } 557 558 /** 559 * Private class to delay initialization of this list until needed. 560 * The circular dependency between Duration and ChronoUnit prevents 561 * the simple initialization in Duration. 562 */ 563 private static class DurationUnits { 564 static final List<TemporalUnit> UNITS = 565 Collections.unmodifiableList(Arrays.<TemporalUnit>asList(SECONDS, NANOS)); 566 } 567 568 //----------------------------------------------------------------------- 569 /** 570 * Checks if this duration is zero length. 571 * <p> 572 * A {@code Duration} represents a directed distance between two points on 573 * the time-line and can therefore be positive, zero or negative. 574 * This method checks whether the length is zero. 575 * 576 * @return true if this duration has a total length equal to zero 577 */ 578 public boolean isZero() { 579 return (seconds | nanos) == 0; 580 } 581 582 /** 583 * Checks if this duration is negative, excluding zero. 584 * <p> 585 * A {@code Duration} represents a directed distance between two points on 586 * the time-line and can therefore be positive, zero or negative. 587 * This method checks whether the length is less than zero. 588 * 589 * @return true if this duration has a total length less than zero 590 */ 591 public boolean isNegative() { 592 return seconds < 0; 593 } 594 595 //----------------------------------------------------------------------- 596 /** 597 * Gets the number of seconds in this duration. 598 * <p> 599 * The length of the duration is stored using two fields - seconds and nanoseconds. 600 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to 601 * the length in seconds. 602 * The total duration is defined by calling this method and {@link #getNano()}. 603 * <p> 604 * A {@code Duration} represents a directed distance between two points on the time-line. 605 * A negative duration is expressed by the negative sign of the seconds part. 606 * A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds. 607 * 608 * @return the whole seconds part of the length of the duration, positive or negative 609 */ 610 public long getSeconds() { 611 return seconds; 612 } 613 614 /** 615 * Gets the number of nanoseconds within the second in this duration. 616 * <p> 617 * The length of the duration is stored using two fields - seconds and nanoseconds. 618 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to 619 * the length in seconds. 620 * The total duration is defined by calling this method and {@link #getSeconds()}. 621 * <p> 622 * A {@code Duration} represents a directed distance between two points on the time-line. 623 * A negative duration is expressed by the negative sign of the seconds part. 624 * A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds. 625 * 626 * @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999 627 */ 628 public int getNano() { 629 return nanos; 630 } 631 632 //----------------------------------------------------------------------- 633 /** 634 * Returns a copy of this duration with the specified amount of seconds. 635 * <p> 636 * This returns a duration with the specified seconds, retaining the 637 * nano-of-second part of this duration. 638 * <p> 639 * This instance is immutable and unaffected by this method call. 640 * 641 * @param seconds the seconds to represent, may be negative 642 * @return a {@code Duration} based on this period with the requested seconds, not null 643 */ 644 public Duration withSeconds(long seconds) { 645 return create(seconds, nanos); 646 } 647 648 /** 649 * Returns a copy of this duration with the specified nano-of-second. 650 * <p> 651 * This returns a duration with the specified nano-of-second, retaining the 652 * seconds part of this duration. 653 * <p> 654 * This instance is immutable and unaffected by this method call. 655 * 656 * @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999 657 * @return a {@code Duration} based on this period with the requested nano-of-second, not null 658 * @throws DateTimeException if the nano-of-second is invalid 659 */ 660 public Duration withNanos(int nanoOfSecond) { 661 NANO_OF_SECOND.checkValidIntValue(nanoOfSecond); 662 return create(seconds, nanoOfSecond); 663 } 664 665 //----------------------------------------------------------------------- 666 /** 667 * Returns a copy of this duration with the specified duration added. 668 * <p> 669 * This instance is immutable and unaffected by this method call. 670 * 671 * @param duration the duration to add, positive or negative, not null 672 * @return a {@code Duration} based on this duration with the specified duration added, not null 673 * @throws ArithmeticException if numeric overflow occurs 674 */ 675 public Duration plus(Duration duration) { 676 return plus(duration.getSeconds(), duration.getNano()); 677 } 678 679 /** 680 * Returns a copy of this duration with the specified duration added. 681 * <p> 682 * The duration amount is measured in terms of the specified unit. 683 * Only a subset of units are accepted by this method. 684 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or 685 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception. 686 * <p> 687 * This instance is immutable and unaffected by this method call. 688 * 689 * @param amountToAdd the amount to add, measured in terms of the unit, positive or negative 690 * @param unit the unit that the amount is measured in, must have an exact duration, not null 691 * @return a {@code Duration} based on this duration with the specified duration added, not null 692 * @throws UnsupportedTemporalTypeException if the unit is not supported 693 * @throws ArithmeticException if numeric overflow occurs 694 */ 695 public Duration plus(long amountToAdd, TemporalUnit unit) { 696 Objects.requireNonNull(unit, "unit"); 697 if (unit == DAYS) { 698 return plus(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY), 0); 699 } 700 if (unit.isDurationEstimated()) { 701 throw new UnsupportedTemporalTypeException("Unit must not have an estimated duration"); 702 } 703 if (amountToAdd == 0) { 704 return this; 705 } 706 if (unit instanceof ChronoUnit) { 707 switch ((ChronoUnit) unit) { 708 case NANOS: return plusNanos(amountToAdd); 709 case MICROS: return plusSeconds((amountToAdd / (1000_000L * 1000)) * 1000).plusNanos((amountToAdd % (1000_000L * 1000)) * 1000); 710 case MILLIS: return plusMillis(amountToAdd); 711 case SECONDS: return plusSeconds(amountToAdd); 712 } 713 return plusSeconds(Math.multiplyExact(unit.getDuration().seconds, amountToAdd)); 714 } 715 Duration duration = unit.getDuration().multipliedBy(amountToAdd); 716 return plusSeconds(duration.getSeconds()).plusNanos(duration.getNano()); 717 } 718 719 //----------------------------------------------------------------------- 720 /** 721 * Returns a copy of this duration with the specified duration in standard 24 hour days added. 722 * <p> 723 * The number of days is multiplied by 86400 to obtain the number of seconds to add. 724 * This is based on the standard definition of a day as 24 hours. 725 * <p> 726 * This instance is immutable and unaffected by this method call. 727 * 728 * @param daysToAdd the days to add, positive or negative 729 * @return a {@code Duration} based on this duration with the specified days added, not null 730 * @throws ArithmeticException if numeric overflow occurs 731 */ 732 public Duration plusDays(long daysToAdd) { 733 return plus(Math.multiplyExact(daysToAdd, SECONDS_PER_DAY), 0); 734 } 735 736 /** 737 * Returns a copy of this duration with the specified duration in hours added. 738 * <p> 739 * This instance is immutable and unaffected by this method call. 740 * 741 * @param hoursToAdd the hours to add, positive or negative 742 * @return a {@code Duration} based on this duration with the specified hours added, not null 743 * @throws ArithmeticException if numeric overflow occurs 744 */ 745 public Duration plusHours(long hoursToAdd) { 746 return plus(Math.multiplyExact(hoursToAdd, SECONDS_PER_HOUR), 0); 747 } 748 749 /** 750 * Returns a copy of this duration with the specified duration in minutes added. 751 * <p> 752 * This instance is immutable and unaffected by this method call. 753 * 754 * @param minutesToAdd the minutes to add, positive or negative 755 * @return a {@code Duration} based on this duration with the specified minutes added, not null 756 * @throws ArithmeticException if numeric overflow occurs 757 */ 758 public Duration plusMinutes(long minutesToAdd) { 759 return plus(Math.multiplyExact(minutesToAdd, SECONDS_PER_MINUTE), 0); 760 } 761 762 /** 763 * Returns a copy of this duration with the specified duration in seconds added. 764 * <p> 765 * This instance is immutable and unaffected by this method call. 766 * 767 * @param secondsToAdd the seconds to add, positive or negative 768 * @return a {@code Duration} based on this duration with the specified seconds added, not null 769 * @throws ArithmeticException if numeric overflow occurs 770 */ 771 public Duration plusSeconds(long secondsToAdd) { 772 return plus(secondsToAdd, 0); 773 } 774 775 /** 776 * Returns a copy of this duration with the specified duration in milliseconds added. 777 * <p> 778 * This instance is immutable and unaffected by this method call. 779 * 780 * @param millisToAdd the milliseconds to add, positive or negative 781 * @return a {@code Duration} based on this duration with the specified milliseconds added, not null 782 * @throws ArithmeticException if numeric overflow occurs 783 */ 784 public Duration plusMillis(long millisToAdd) { 785 return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000); 786 } 787 788 /** 789 * Returns a copy of this duration with the specified duration in nanoseconds added. 790 * <p> 791 * This instance is immutable and unaffected by this method call. 792 * 793 * @param nanosToAdd the nanoseconds to add, positive or negative 794 * @return a {@code Duration} based on this duration with the specified nanoseconds added, not null 795 * @throws ArithmeticException if numeric overflow occurs 796 */ 797 public Duration plusNanos(long nanosToAdd) { 798 return plus(0, nanosToAdd); 799 } 800 801 /** 802 * Returns a copy of this duration with the specified duration added. 803 * <p> 804 * This instance is immutable and unaffected by this method call. 805 * 806 * @param secondsToAdd the seconds to add, positive or negative 807 * @param nanosToAdd the nanos to add, positive or negative 808 * @return a {@code Duration} based on this duration with the specified seconds added, not null 809 * @throws ArithmeticException if numeric overflow occurs 810 */ 811 private Duration plus(long secondsToAdd, long nanosToAdd) { 812 if ((secondsToAdd | nanosToAdd) == 0) { 813 return this; 814 } 815 long epochSec = Math.addExact(seconds, secondsToAdd); 816 epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND); 817 nanosToAdd = nanosToAdd % NANOS_PER_SECOND; 818 long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND 819 return ofSeconds(epochSec, nanoAdjustment); 820 } 821 822 //----------------------------------------------------------------------- 823 /** 824 * Returns a copy of this duration with the specified duration subtracted. 825 * <p> 826 * This instance is immutable and unaffected by this method call. 827 * 828 * @param duration the duration to subtract, positive or negative, not null 829 * @return a {@code Duration} based on this duration with the specified duration subtracted, not null 830 * @throws ArithmeticException if numeric overflow occurs 831 */ 832 public Duration minus(Duration duration) { 833 long secsToSubtract = duration.getSeconds(); 834 int nanosToSubtract = duration.getNano(); 835 if (secsToSubtract == Long.MIN_VALUE) { 836 return plus(Long.MAX_VALUE, -nanosToSubtract).plus(1, 0); 837 } 838 return plus(-secsToSubtract, -nanosToSubtract); 839 } 840 841 /** 842 * Returns a copy of this duration with the specified duration subtracted. 843 * <p> 844 * The duration amount is measured in terms of the specified unit. 845 * Only a subset of units are accepted by this method. 846 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or 847 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception. 848 * <p> 849 * This instance is immutable and unaffected by this method call. 850 * 851 * @param amountToSubtract the amount to subtract, measured in terms of the unit, positive or negative 852 * @param unit the unit that the amount is measured in, must have an exact duration, not null 853 * @return a {@code Duration} based on this duration with the specified duration subtracted, not null 854 * @throws ArithmeticException if numeric overflow occurs 855 */ 856 public Duration minus(long amountToSubtract, TemporalUnit unit) { 857 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); 858 } 859 860 //----------------------------------------------------------------------- 861 /** 862 * Returns a copy of this duration with the specified duration in standard 24 hour days subtracted. 863 * <p> 864 * The number of days is multiplied by 86400 to obtain the number of seconds to subtract. 865 * This is based on the standard definition of a day as 24 hours. 866 * <p> 867 * This instance is immutable and unaffected by this method call. 868 * 869 * @param daysToSubtract the days to subtract, positive or negative 870 * @return a {@code Duration} based on this duration with the specified days subtracted, not null 871 * @throws ArithmeticException if numeric overflow occurs 872 */ 873 public Duration minusDays(long daysToSubtract) { 874 return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract)); 875 } 876 877 /** 878 * Returns a copy of this duration with the specified duration in hours subtracted. 879 * <p> 880 * The number of hours is multiplied by 3600 to obtain the number of seconds to subtract. 881 * <p> 882 * This instance is immutable and unaffected by this method call. 883 * 884 * @param hoursToSubtract the hours to subtract, positive or negative 885 * @return a {@code Duration} based on this duration with the specified hours subtracted, not null 886 * @throws ArithmeticException if numeric overflow occurs 887 */ 888 public Duration minusHours(long hoursToSubtract) { 889 return (hoursToSubtract == Long.MIN_VALUE ? plusHours(Long.MAX_VALUE).plusHours(1) : plusHours(-hoursToSubtract)); 890 } 891 892 /** 893 * Returns a copy of this duration with the specified duration in minutes subtracted. 894 * <p> 895 * The number of hours is multiplied by 60 to obtain the number of seconds to subtract. 896 * <p> 897 * This instance is immutable and unaffected by this method call. 898 * 899 * @param minutesToSubtract the minutes to subtract, positive or negative 900 * @return a {@code Duration} based on this duration with the specified minutes subtracted, not null 901 * @throws ArithmeticException if numeric overflow occurs 902 */ 903 public Duration minusMinutes(long minutesToSubtract) { 904 return (minutesToSubtract == Long.MIN_VALUE ? plusMinutes(Long.MAX_VALUE).plusMinutes(1) : plusMinutes(-minutesToSubtract)); 905 } 906 907 /** 908 * Returns a copy of this duration with the specified duration in seconds subtracted. 909 * <p> 910 * This instance is immutable and unaffected by this method call. 911 * 912 * @param secondsToSubtract the seconds to subtract, positive or negative 913 * @return a {@code Duration} based on this duration with the specified seconds subtracted, not null 914 * @throws ArithmeticException if numeric overflow occurs 915 */ 916 public Duration minusSeconds(long secondsToSubtract) { 917 return (secondsToSubtract == Long.MIN_VALUE ? plusSeconds(Long.MAX_VALUE).plusSeconds(1) : plusSeconds(-secondsToSubtract)); 918 } 919 920 /** 921 * Returns a copy of this duration with the specified duration in milliseconds subtracted. 922 * <p> 923 * This instance is immutable and unaffected by this method call. 924 * 925 * @param millisToSubtract the milliseconds to subtract, positive or negative 926 * @return a {@code Duration} based on this duration with the specified milliseconds subtracted, not null 927 * @throws ArithmeticException if numeric overflow occurs 928 */ 929 public Duration minusMillis(long millisToSubtract) { 930 return (millisToSubtract == Long.MIN_VALUE ? plusMillis(Long.MAX_VALUE).plusMillis(1) : plusMillis(-millisToSubtract)); 931 } 932 933 /** 934 * Returns a copy of this duration with the specified duration in nanoseconds subtracted. 935 * <p> 936 * This instance is immutable and unaffected by this method call. 937 * 938 * @param nanosToSubtract the nanoseconds to subtract, positive or negative 939 * @return a {@code Duration} based on this duration with the specified nanoseconds subtracted, not null 940 * @throws ArithmeticException if numeric overflow occurs 941 */ 942 public Duration minusNanos(long nanosToSubtract) { 943 return (nanosToSubtract == Long.MIN_VALUE ? plusNanos(Long.MAX_VALUE).plusNanos(1) : plusNanos(-nanosToSubtract)); 944 } 945 946 //----------------------------------------------------------------------- 947 /** 948 * Returns a copy of this duration multiplied by the scalar. 949 * <p> 950 * This instance is immutable and unaffected by this method call. 951 * 952 * @param multiplicand the value to multiply the duration by, positive or negative 953 * @return a {@code Duration} based on this duration multiplied by the specified scalar, not null 954 * @throws ArithmeticException if numeric overflow occurs 955 */ 956 public Duration multipliedBy(long multiplicand) { 957 if (multiplicand == 0) { 958 return ZERO; 959 } 960 if (multiplicand == 1) { 961 return this; 962 } 963 return create(toSeconds().multiply(BigDecimal.valueOf(multiplicand))); 964 } 965 966 /** 967 * Returns a copy of this duration divided by the specified value. 968 * <p> 969 * This instance is immutable and unaffected by this method call. 970 * 971 * @param divisor the value to divide the duration by, positive or negative, not zero 972 * @return a {@code Duration} based on this duration divided by the specified divisor, not null 973 * @throws ArithmeticException if the divisor is zero or if numeric overflow occurs 974 */ 975 public Duration dividedBy(long divisor) { 976 if (divisor == 0) { 977 throw new ArithmeticException("Cannot divide by zero"); 978 } 979 if (divisor == 1) { 980 return this; 981 } 982 return create(toSeconds().divide(BigDecimal.valueOf(divisor), RoundingMode.DOWN)); 983 } 984 985 /** 986 * Converts this duration to the total length in seconds and 987 * fractional nanoseconds expressed as a {@code BigDecimal}. 988 * 989 * @return the total length of the duration in seconds, with a scale of 9, not null 990 */ 991 private BigDecimal toSeconds() { 992 return BigDecimal.valueOf(seconds).add(BigDecimal.valueOf(nanos, 9)); 993 } 994 995 /** 996 * Creates an instance of {@code Duration} from a number of seconds. 997 * 998 * @param seconds the number of seconds, up to scale 9, positive or negative 999 * @return a {@code Duration}, not null 1000 * @throws ArithmeticException if numeric overflow occurs 1001 */ 1002 private static Duration create(BigDecimal seconds) { 1003 BigInteger nanos = seconds.movePointRight(9).toBigIntegerExact(); 1004 BigInteger[] divRem = nanos.divideAndRemainder(BI_NANOS_PER_SECOND); 1005 if (divRem[0].bitLength() > 63) { 1006 throw new ArithmeticException("Exceeds capacity of Duration: " + nanos); 1007 } 1008 return ofSeconds(divRem[0].longValue(), divRem[1].intValue()); 1009 } 1010 1011 //----------------------------------------------------------------------- 1012 /** 1013 * Returns a copy of this duration with the length negated. 1014 * <p> 1015 * This method swaps the sign of the total length of this duration. 1016 * For example, {@code PT1.3S} will be returned as {@code PT-1.3S}. 1017 * <p> 1018 * This instance is immutable and unaffected by this method call. 1019 * 1020 * @return a {@code Duration} based on this duration with the amount negated, not null 1021 * @throws ArithmeticException if numeric overflow occurs 1022 */ 1023 public Duration negated() { 1024 return multipliedBy(-1); 1025 } 1026 1027 /** 1028 * Returns a copy of this duration with a positive length. 1029 * <p> 1030 * This method returns a positive duration by effectively removing the sign from any negative total length. 1031 * For example, {@code PT-1.3S} will be returned as {@code PT1.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 an absolute length, not null 1036 * @throws ArithmeticException if numeric overflow occurs 1037 */ 1038 public Duration abs() { 1039 return isNegative() ? negated() : this; 1040 } 1041 1042 //------------------------------------------------------------------------- 1043 /** 1044 * Adds this duration to the specified temporal object. 1045 * <p> 1046 * This returns a temporal object of the same observable type as the input 1047 * with this duration added. 1048 * <p> 1049 * In most cases, it is clearer to reverse the calling pattern by using 1050 * {@link Temporal#plus(TemporalAmount)}. 1051 * <pre> 1052 * // these two lines are equivalent, but the second approach is recommended 1053 * dateTime = thisDuration.addTo(dateTime); 1054 * dateTime = dateTime.plus(thisDuration); 1055 * </pre> 1056 * <p> 1057 * The calculation will add the seconds, then nanos. 1058 * Only non-zero amounts will be added. 1059 * <p> 1060 * This instance is immutable and unaffected by this method call. 1061 * 1062 * @param temporal the temporal object to adjust, not null 1063 * @return an object of the same type with the adjustment made, not null 1064 * @throws DateTimeException if unable to add 1065 * @throws ArithmeticException if numeric overflow occurs 1066 */ 1067 @Override 1068 public Temporal addTo(Temporal temporal) { 1069 if (seconds != 0) { 1070 temporal = temporal.plus(seconds, SECONDS); 1071 } 1072 if (nanos != 0) { 1073 temporal = temporal.plus(nanos, NANOS); 1074 } 1075 return temporal; 1076 } 1077 1078 /** 1079 * Subtracts this duration from the specified temporal object. 1080 * <p> 1081 * This returns a temporal object of the same observable type as the input 1082 * with this duration subtracted. 1083 * <p> 1084 * In most cases, it is clearer to reverse the calling pattern by using 1085 * {@link Temporal#minus(TemporalAmount)}. 1086 * <pre> 1087 * // these two lines are equivalent, but the second approach is recommended 1088 * dateTime = thisDuration.subtractFrom(dateTime); 1089 * dateTime = dateTime.minus(thisDuration); 1090 * </pre> 1091 * <p> 1092 * The calculation will subtract the seconds, then nanos. 1093 * Only non-zero amounts will be added. 1094 * <p> 1095 * This instance is immutable and unaffected by this method call. 1096 * 1097 * @param temporal the temporal object to adjust, not null 1098 * @return an object of the same type with the adjustment made, not null 1099 * @throws DateTimeException if unable to subtract 1100 * @throws ArithmeticException if numeric overflow occurs 1101 */ 1102 @Override 1103 public Temporal subtractFrom(Temporal temporal) { 1104 if (seconds != 0) { 1105 temporal = temporal.minus(seconds, SECONDS); 1106 } 1107 if (nanos != 0) { 1108 temporal = temporal.minus(nanos, NANOS); 1109 } 1110 return temporal; 1111 } 1112 1113 //----------------------------------------------------------------------- 1114 /** 1115 * Gets the number of days in this duration. 1116 * <p> 1117 * This returns the total number of days in the duration by dividing the 1118 * number of seconds by 86400. 1119 * This is based on the standard definition of a day as 24 hours. 1120 * <p> 1121 * This instance is immutable and unaffected by this method call. 1122 * 1123 * @return the number of days in the duration, may be negative 1124 */ 1125 public long toDays() { 1126 return seconds / SECONDS_PER_DAY; 1127 } 1128 1129 /** 1130 * Gets the number of hours in this duration. 1131 * <p> 1132 * This returns the total number of hours in the duration by dividing the 1133 * number of seconds by 3600. 1134 * <p> 1135 * This instance is immutable and unaffected by this method call. 1136 * 1137 * @return the number of hours in the duration, may be negative 1138 */ 1139 public long toHours() { 1140 return seconds / SECONDS_PER_HOUR; 1141 } 1142 1143 /** 1144 * Gets the number of minutes in this duration. 1145 * <p> 1146 * This returns the total number of minutes in the duration by dividing the 1147 * number of seconds by 60. 1148 * <p> 1149 * This instance is immutable and unaffected by this method call. 1150 * 1151 * @return the number of minutes in the duration, may be negative 1152 */ 1153 public long toMinutes() { 1154 return seconds / SECONDS_PER_MINUTE; 1155 } 1156 1157 /** 1158 * Converts this duration to the total length in milliseconds. 1159 * <p> 1160 * If this duration is too large to fit in a {@code long} milliseconds, then an 1161 * exception is thrown. 1162 * <p> 1163 * If this duration has greater than millisecond precision, then the conversion 1164 * will drop any excess precision information as though the amount in nanoseconds 1165 * was subject to integer division by one million. 1166 * 1167 * @return the total length of the duration in milliseconds 1168 * @throws ArithmeticException if numeric overflow occurs 1169 */ 1170 public long toMillis() { 1171 long millis = Math.multiplyExact(seconds, 1000); 1172 millis = Math.addExact(millis, nanos / 1000_000); 1173 return millis; 1174 } 1175 1176 /** 1177 * Converts this duration to the total length in nanoseconds expressed as a {@code long}. 1178 * <p> 1179 * If this duration is too large to fit in a {@code long} nanoseconds, then an 1180 * exception is thrown. 1181 * 1182 * @return the total length of the duration in nanoseconds 1183 * @throws ArithmeticException if numeric overflow occurs 1184 */ 1185 public long toNanos() { 1186 long totalNanos = Math.multiplyExact(seconds, NANOS_PER_SECOND); 1187 totalNanos = Math.addExact(totalNanos, nanos); 1188 return totalNanos; 1189 } 1190 1191 //----------------------------------------------------------------------- 1192 /** 1193 * Compares this duration to the specified {@code Duration}. 1194 * <p> 1195 * The comparison is based on the total length of the durations. 1196 * It is "consistent with equals", as defined by {@link Comparable}. 1197 * 1198 * @param otherDuration the other duration to compare to, not null 1199 * @return the comparator value, negative if less, positive if greater 1200 */ 1201 @Override 1202 public int compareTo(Duration otherDuration) { 1203 int cmp = Long.compare(seconds, otherDuration.seconds); 1204 if (cmp != 0) { 1205 return cmp; 1206 } 1207 return nanos - otherDuration.nanos; 1208 } 1209 1210 //----------------------------------------------------------------------- 1211 /** 1212 * Checks if this duration is equal to the specified {@code Duration}. 1213 * <p> 1214 * The comparison is based on the total length of the durations. 1215 * 1216 * @param otherDuration the other duration, null returns false 1217 * @return true if the other duration is equal to this one 1218 */ 1219 @Override 1220 public boolean equals(Object otherDuration) { 1221 if (this == otherDuration) { 1222 return true; 1223 } 1224 if (otherDuration instanceof Duration) { 1225 Duration other = (Duration) otherDuration; 1226 return this.seconds == other.seconds && 1227 this.nanos == other.nanos; 1228 } 1229 return false; 1230 } 1231 1232 /** 1233 * A hash code for this duration. 1234 * 1235 * @return a suitable hash code 1236 */ 1237 @Override 1238 public int hashCode() { 1239 return ((int) (seconds ^ (seconds >>> 32))) + (51 * nanos); 1240 } 1241 1242 //----------------------------------------------------------------------- 1243 /** 1244 * A string representation of this duration using ISO-8601 seconds 1245 * based representation, such as {@code PT8H6M12.345S}. 1246 * <p> 1247 * The format of the returned string will be {@code PTnHnMnS}, where n is 1248 * the relevant hours, minutes or seconds part of the duration. 1249 * Any fractional seconds are placed after a decimal point i the seconds section. 1250 * If a section has a zero value, it is omitted. 1251 * The hours, minutes and seconds will all have the same sign. 1252 * <p> 1253 * Examples: 1254 * <pre> 1255 * "20.345 seconds" -- "PT20.345S 1256 * "15 minutes" (15 * 60 seconds) -- "PT15M" 1257 * "10 hours" (10 * 3600 seconds) -- "PT10H" 1258 * "2 days" (2 * 86400 seconds) -- "PT48H" 1259 * </pre> 1260 * Note that multiples of 24 hours are not output as days to avoid confusion 1261 * with {@code Period}. 1262 * 1263 * @return an ISO-8601 representation of this duration, not null 1264 */ 1265 @Override 1266 public String toString() { 1267 if (this == ZERO) { 1268 return "PT0S"; 1269 } 1270 long hours = seconds / SECONDS_PER_HOUR; 1271 int minutes = (int) ((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE); 1272 int secs = (int) (seconds % SECONDS_PER_MINUTE); 1273 StringBuilder buf = new StringBuilder(24); 1274 buf.append("PT"); 1275 if (hours != 0) { 1276 buf.append(hours).append('H'); 1277 } 1278 if (minutes != 0) { 1279 buf.append(minutes).append('M'); 1280 } 1281 if (secs == 0 && nanos == 0 && buf.length() > 2) { 1282 return buf.toString(); 1283 } 1284 if (secs < 0 && nanos > 0) { 1285 if (secs == -1) { 1286 buf.append("-0"); 1287 } else { 1288 buf.append(secs + 1); 1289 } 1290 } else { 1291 buf.append(secs); 1292 } 1293 if (nanos > 0) { 1294 int pos = buf.length(); 1295 if (secs < 0) { 1296 buf.append(2 * NANOS_PER_SECOND - nanos); 1297 } else { 1298 buf.append(nanos + NANOS_PER_SECOND); 1299 } 1300 while (buf.charAt(buf.length() - 1) == '0') { 1301 buf.setLength(buf.length() - 1); 1302 } 1303 buf.setCharAt(pos, '.'); 1304 } 1305 buf.append('S'); 1306 return buf.toString(); 1307 } 1308 1309 //----------------------------------------------------------------------- 1310 /** 1311 * Writes the object using a 1312 * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>. 1313 * @serialData 1314 * <pre> 1315 * out.writeByte(1); // identifies a Duration 1316 * out.writeLong(seconds); 1317 * out.writeInt(nanos); 1318 * </pre> 1319 * 1320 * @return the instance of {@code Ser}, not null 1321 */ 1322 private Object writeReplace() { 1323 return new Ser(Ser.DURATION_TYPE, this); 1324 } 1325 1326 /** 1327 * Defend against malicious streams. 1328 * 1329 * @param s the stream to read 1330 * @throws InvalidObjectException always 1331 */ 1332 private void readObject(ObjectInputStream s) throws InvalidObjectException { 1333 throw new InvalidObjectException("Deserialization via serialization delegate"); 1334 } 1335 1336 void writeExternal(DataOutput out) throws IOException { 1337 out.writeLong(seconds); 1338 out.writeInt(nanos); 1339 } 1340 1341 static Duration readExternal(DataInput in) throws IOException { 1342 long seconds = in.readLong(); 1343 int nanos = in.readInt(); 1344 return Duration.ofSeconds(seconds, nanos); 1345 } 1346 1347 }