Duration Conversion with java.util.concurrent.TimeUnit 📎
As an example, the following test converts three seconds to milliseconds:
@Test
public void secondsToMs() {
var expected = 3 * 1000;
var actual = TimeUnit.SECONDS.toMillis(3);
assertEquals(expected, actual);
}
Now from milliseconds to minutes:
@Test
public void msToMinutes() {
var expected = 3;
var actual = TimeUnit.MILLISECONDS.toMinutes(180000);
assertEquals(expected, actual);
}
With TimeUnit
we can even wait for the next vacations:
@Test
public void sleepWithTimeUnitForThreeSeconds() throws InterruptedException {
long start = System.currentTimeMillis();
TimeUnit.SECONDS.sleep(3);
//TimeUnit.DAYS.sleep(300); :-)
var duration = System.currentTimeMillis() - start;
assertTrue(duration >= 3000);
}