diff --git a/src/main/java/org/apache/commons/lang3/time/DurationUtils.java b/src/main/java/org/apache/commons/lang3/time/DurationUtils.java index a3e227f49..5ac7f47dc 100644 --- a/src/main/java/org/apache/commons/lang3/time/DurationUtils.java +++ b/src/main/java/org/apache/commons/lang3/time/DurationUtils.java @@ -22,6 +22,7 @@ import java.time.temporal.ChronoUnit; import java.util.Objects; import java.util.concurrent.TimeUnit; +import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.Range; import org.apache.commons.lang3.math.NumberUtils; @@ -108,4 +109,14 @@ public class DurationUtils { return LONG_TO_INT_RANGE.fit(Long.valueOf(duration.toMillis())).intValue(); } + /** + * Returns the given non-null value or {@link Duration#ZERO} if null. + * + * @param duration The duration to test. + * @return The given duration or {@link Duration#ZERO}. + */ + public static Duration zeroIfNull(final Duration duration) { + return ObjectUtils.defaultIfNull(duration, Duration.ZERO); + } + } diff --git a/src/test/java/org/apache/commons/lang3/time/DurationUtilsTest.java b/src/test/java/org/apache/commons/lang3/time/DurationUtilsTest.java index 8202ec8c8..0a9bb8437 100644 --- a/src/test/java/org/apache/commons/lang3/time/DurationUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/time/DurationUtilsTest.java @@ -70,7 +70,7 @@ public class DurationUtilsTest { assertEquals(-1, DurationUtils.toDuration(-1, TimeUnit.MILLISECONDS).toMillis()); assertEquals(0, DurationUtils.toDuration(0, TimeUnit.SECONDS).toMillis()); } - + @Test public void testToMillisInt() { assertEquals(0, DurationUtils.toMillisInt(Duration.ZERO)); @@ -86,4 +86,10 @@ public class DurationUtilsTest { assertEquals(Integer.MIN_VALUE, DurationUtils.toMillisInt(Duration.ofNanos(Long.MIN_VALUE))); assertEquals(Integer.MAX_VALUE, DurationUtils.toMillisInt(Duration.ofNanos(Long.MAX_VALUE))); } + + @Test + public void testZeroIfNull() { + assertEquals(Duration.ZERO, DurationUtils.zeroIfNull(null)); + assertEquals(Duration.ofDays(1), DurationUtils.zeroIfNull(Duration.ofDays(1))); + } }