Duration Conversion with java.util.concurrent.TimeUnit

java.util.concurrent.TimeUnit provides methods to convert across various time units.

As an example, the following test converts three seconds to milliseconds:

public void secondsToMs() {
    var expected = 3 * 1000;
    var actual = TimeUnit.SECONDS.toMillis(3);
    assertEquals(expected, actual);

Now from milliseconds to minutes:

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:

public void sleepWithTimeUnitForThreeSeconds() throws InterruptedException {
    long start = System.currentTimeMillis();
    //TimeUnit.DAYS.sleep(300); :-)

    var duration = System.currentTimeMillis() - start;
    assertTrue(duration >= 3000);


Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments