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 5bf2ebbae..afb3804a5 100644 --- a/src/main/java/org/apache/commons/lang3/time/DurationUtils.java +++ b/src/main/java/org/apache/commons/lang3/time/DurationUtils.java @@ -56,7 +56,7 @@ public class DurationUtils { public static void accept(final FailableBiConsumer consumer, final Duration duration) throws T { if (consumer != null && duration != null) { - consumer.accept(duration.toMillis(), getNanosOfMiili(duration)); + consumer.accept(duration.toMillis(), getNanosOfMilli(duration)); } } @@ -72,8 +72,28 @@ public class DurationUtils { * * @param duration The duration to query. * @return nanoseconds between 0 and 999,999. + * @deprecated Use {@link #getNanosOfMilli(Duration)}. */ + @Deprecated public static int getNanosOfMiili(final Duration duration) { + return getNanosOfMilli(duration); + } + + /** + * Gets the nanosecond part of a Duration converted to milliseconds. + *

+ * Handy when calling an API that takes a long of milliseconds and an int of nanoseconds. For example, + * {@link Object#wait(long, int)} and {@link Thread#sleep(long, int)}. + *

+ *

+ * Note that is this different from {@link Duration#getNano()} because a duration are seconds and nanoseconds. + *

+ * + * @param duration The duration to query. + * @return nanoseconds between 0 and 999,999. + * @since 3.13.0 + */ + public static int getNanosOfMilli(final Duration duration) { return zeroIfNull(duration).getNano() % 1_000_000; } 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 89023e9b6..d3d8f3126 100644 --- a/src/test/java/org/apache/commons/lang3/time/DurationUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/time/DurationUtilsTest.java @@ -38,6 +38,20 @@ public class DurationUtilsTest extends AbstractLangTest { @Test public void testGetNanosOfMilli() { + assertEquals(0, DurationUtils.getNanosOfMilli(null)); + assertEquals(0, DurationUtils.getNanosOfMilli(Duration.ZERO)); + assertEquals(1, DurationUtils.getNanosOfMilli(Duration.ofNanos(1))); + assertEquals(10, DurationUtils.getNanosOfMilli(Duration.ofNanos(10))); + assertEquals(100, DurationUtils.getNanosOfMilli(Duration.ofNanos(100))); + assertEquals(1_000, DurationUtils.getNanosOfMilli(Duration.ofNanos(1_000))); + assertEquals(10_000, DurationUtils.getNanosOfMilli(Duration.ofNanos(10_000))); + assertEquals(100_000, DurationUtils.getNanosOfMilli(Duration.ofNanos(100_000))); + assertEquals(0, DurationUtils.getNanosOfMilli(Duration.ofNanos(1_000_000))); + assertEquals(1, DurationUtils.getNanosOfMilli(Duration.ofNanos(1_000_001))); + } + + @Test + public void testGetNanosOfMiili() { assertEquals(0, DurationUtils.getNanosOfMiili(null)); assertEquals(0, DurationUtils.getNanosOfMiili(Duration.ZERO)); assertEquals(1, DurationUtils.getNanosOfMiili(Duration.ofNanos(1)));