< prev index next >

src/java.base/share/classes/java/time/Duration.java

Print this page

        

@@ -1,7 +1,7 @@
 /*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
  * published by the Free Software Foundation.  Oracle designates this

@@ -1212,12 +1212,20 @@
      *
      * @return the total length of the duration in milliseconds
      * @throws ArithmeticException if numeric overflow occurs
      */
     public long toMillis() {
-        long millis = Math.multiplyExact(seconds, 1000);
-        millis = Math.addExact(millis, nanos / 1000_000);
+        long tempSeconds = seconds;
+        long tempNanos = nanos;
+        if (tempSeconds < 0) {
+            // change the seconds and nano value to
+            // handle Long.MIN_VALUE case
+            tempSeconds = tempSeconds + 1;
+            tempNanos = tempNanos - 1000_000_000L;
+        }
+        long millis = Math.multiplyExact(tempSeconds, 1000);
+        millis = Math.addExact(millis, tempNanos / 1000_000);
         return millis;
     }
 
     /**
      * Converts this duration to the total length in nanoseconds expressed as a {@code long}.

@@ -1227,12 +1235,20 @@
      *
      * @return the total length of the duration in nanoseconds
      * @throws ArithmeticException if numeric overflow occurs
      */
     public long toNanos() {
-        long totalNanos = Math.multiplyExact(seconds, NANOS_PER_SECOND);
-        totalNanos = Math.addExact(totalNanos, nanos);
+        long tempSeconds = seconds;
+        long tempNanos = nanos;
+        if (tempSeconds < 0) {
+            // change the seconds and nano value to
+            // handle Long.MIN_VALUE case
+            tempSeconds = tempSeconds + 1;
+            tempNanos = tempNanos - 1000_000_000L;
+        }
+        long totalNanos = Math.multiplyExact(tempSeconds, NANOS_PER_SECOND);
+        totalNanos = Math.addExact(totalNanos, tempNanos);
         return totalNanos;
     }
 
     /**
      * Extracts the number of days in the duration.
< prev index next >