Convert "duration" "Unit" to milliseconds

xenoterracide picture xenoterracide · Jun 9, 2016 · Viewed 22.8k times · Source

I want to have an API that looks like

public static long toMillis ( long duration, ChronoUnit unit ) {
   // magic duration to millis
}

toMillis( 5, ChronoUnit.SECONDS); // 5000

of course I'm not actually writing toMillis but that's essentially what I'm trying to do.

Answer

Andrew Rueckert picture Andrew Rueckert · Jun 9, 2016

You can use Duration for this:

Duration.of(5, ChronoUnit.SECONDS).toMillis()