ylbtech-Java-Class-FC:java.time.Duration
1.返回顶部
 
2.返回顶部
 
3.返回顶部
1、
  1. /*
  2. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
  3. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. *
  5. *
  6. *
  7. *
  8. *
  9. *
  10. *
  11. *
  12. *
  13. *
  14. *
  15. *
  16. *
  17. *
  18. *
  19. *
  20. *
  21. *
  22. *
  23. *
  24. */
  25.  
  26. /*
  27. *
  28. *
  29. *
  30. *
  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. }
2、
4.返回顶部
 
5.返回顶部
 
 
6.返回顶部
 
作者:ylbtech
出处:http://ylbtech.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

Java-Class-FC:java.time.Duration的更多相关文章

  1. Java总结篇:Java多线程

    Java总结篇系列:Java多线程 多线程作为Java中很重要的一个知识点,在此还是有必要总结一下的. 一.线程的生命周期及五种基本状态 关于Java中线程的生命周期,首先看一下下面这张较为经典的图: ...

  2. 转 Java虚拟机5:Java垃圾回收(GC)机制详解

    转 Java虚拟机5:Java垃圾回收(GC)机制详解 Java虚拟机5:Java垃圾回收(GC)机制详解 哪些内存需要回收? 哪些内存需要回收是垃圾回收机制第一个要考虑的问题,所谓“要回收的垃圾”无 ...

  3. Java并发编程:Java的四种线程池的使用,以及自定义线程工厂

    目录 引言 四种线程池 newCachedThreadPool:可缓存的线程池 newFixedThreadPool:定长线程池 newSingleThreadExecutor:单线程线程池 newS ...

  4. Java虚拟机2:Java内存区域

    1.几个计算机的概念 为以后写文章考虑,也为巩固自己的知识和一些基本概念,这里要理清楚几个计算机中的概念. 1.计算机存储单位 从小到大依次为位Bit.字节Byte.千字节KB.兆M.千兆GB.TB, ...

  5. Java调用本地接口:java.lang.UnsatisfiedLinkError

    Java调用本地接口:java.lang.UnsatisfiedLinkError 我的问题不在这篇文章描述中, 而是因为jni原来是c实现, 现在切换到cpp了, 需要在对应的cpp文件中加入ext ...

  6. Java基础16:Java多线程基础最全总结

    Java基础16:Java多线程基础最全总结 Java中的线程 Java之父对线程的定义是: 线程是一个独立执行的调用序列,同一个进程的线程在同一时刻共享一些系统资源(比如文件句柄等)也能访问同一个进 ...

  7. Java基础教程:Java内存区域

    Java基础教程:Java内存区域 运行时数据区域 Java虚拟机在执行Java程序的过程种会把它所管理的内存划分为若干个不同的数据区域.这些区域都有各自的用途,以及创建和销毁的时间,有的区域随着虚拟 ...

  8. jsp(java server pages):java服务器端的页面

    jsp(java server pages):java服务器端的页面 JSP的执行过程1.浏览器输入一个jsp页面2.tomcat会接受*.jsp请求,将该请求发送到org.apache.jasper ...

  9. JAVA基础语法:java编程规范和常用数据类型(转载)

    JAVA基础语法:java编程规范和常用数据类型 摘要 本文主要介绍了最基本的java程序规则,和常用数据类型,其中侧重说了数组的一些操作. 面向java编程 java是纯面向对象语言,所有的程序都要 ...

  10. Java程序日志:java.util.logging.Logger类

    一.Logger 的级别 比log4j的级别详细,全部定义在java.util.logging.Level里面.各级别按降序排列如下:SEVERE(最高值)WARNINGINFOCONFIGFINEF ...

随机推荐

  1. [CSP-S模拟测试]:队长快跑(DP+离散化+线段树)

    题目背景 传说中,在远古时代,巨龙大$Y$将$P$国的镇国之宝窃走并藏在了其巢穴中,这吸引着整个$P$国的所有冒险家前去夺回,尤其是皇家卫士队的队长小$W$.在$P$国量子科技实验室的帮助下,队长小$ ...

  2. 2018icpc沈阳/gym101955 J How Much Memory Your Code Is Using? 签到

    题意: 给你定义一堆变量,计算一下这些变量共占了多少k内存. 题解: 按题意模拟即可,善用ceil() // // Created by melon on 2019/10/22. // #includ ...

  3. C++ placement new与内存池

    参考:https://blog.csdn.net/Kiritow/article/details/51314612 有些时候我们需要能够长时间运行的程序(例如监听程序,服务器程序)对于这些7*24运行 ...

  4. 用Python实现一个简单的猜数字游戏

    import random number = int(random.uniform(1,10)) attempt = 0 while (attempt < 3): m = int(input(' ...

  5. Cocos2d之运行Test项目

    |   版权声明:本文为博主原创文章,未经博主允许不得转载. 1. 打开Test项目 路径为   C:\Dev\cocos2d-x-3.8.1\build 2.设定cpp-tests为启动项(当cpp ...

  6. WEB前端资源集

    原出处:http://www.cnblogs.com/zhengjialux/archive/2017/01/16/6291394.html 资源网站篇 CSDN:全球最大中文IT社区,为IT专业技术 ...

  7. MUI对话框使用

    一.alert告警框 用法 .alert(message,title,btnvalue,callback[,type]); document.getElementById("noclick& ...

  8. vue对象侦测

    http://blog.csdn.net/yihanzhi/article/details/74200618 数组:this.$set(this.arr,index,value)

  9. 为什么要用webpack!

    为什么要用webpack?   现今的很多网页其实可以看做是功能丰富的应用,它们拥有着复杂的JavaScript代码和一大堆依赖包. 模块化,让我们可以把复杂的程序细化为小的文件;   类似于Type ...

  10. Leetcode 算法题

    lEETCODE 算法题 0013 罗马数字转整数