Java Utililty Methods Duration Calculate

List of utility methods to do Duration Calculate

Description

The list of methods to do Duration Calculate are organized into topic(s).

Method

DurationadjustServerTimeout(Duration clientTimeout)
adjust Server Timeout
return clientTimeout.minusMillis(100);
booleanawaitTermination(ExecutorService service, Logger logger, Duration timeout, String technique)
Await termination of the given ExecutorService .
try {
    service.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS);
    return true;
} catch (InterruptedException e) {
    logger.severe(technique + " shutdown of " + service + " did not complete within " + timeout);
    return false;
DurationcalculateDuration(Duration minimum, Duration maximum, Long iteration)
calculate Duration
Duration candidate = minimum.multipliedBy((long) Math.pow(2, iteration));
return min(candidate, maximum);
longdaysRoundingUp(Duration duration)
days Rounding Up
final long days = duration.toDays();
return duration.equals(Duration.ofDays(days)) ? days : days + 1;
CompletableFuturedelayedFuture(Duration delay, ScheduledExecutorService executorService)
Creates a CompletableFuture that will do nothing and complete after a specified delay, without using a thread during the delay.
CompletableFuture<Void> result = new CompletableFuture<>();
if (delay.toMillis() == 0) {
    result.complete(null);
} else {
    ScheduledFuture<Boolean> sf = executorService.schedule(() -> result.complete(null), delay.toMillis(),
            TimeUnit.MILLISECONDS);
    result.whenComplete((r, ex) -> sf.cancel(true));
return result;
longdurationFromNow(TemporalAmount duration)
duration From Now
return LocalDateTime.now(ZoneId.of("UTC")).plus(duration).toEpochSecond(ZoneOffset.UTC);
CompletableFuturefailAfter(Duration duration)
Generates a completable future which times out.
final CompletableFuture<T> promise = new CompletableFuture<>();
scheduler.schedule(() -> {
    final TimeoutException ex = new TimeoutException("Timeout after " + duration.toMillis() + " ms");
    return promise.completeExceptionally(ex);
}, duration.toMillis(), TimeUnit.MILLISECONDS);
return promise;
CompletableFuturefutureWithTimeout(Duration timeout, ScheduledExecutorService executorService)
Creates a new CompletableFuture that will timeout after the given amount of time.
return futureWithTimeout(timeout, null, executorService);
StringgetDurationAsISO8601(Duration duration)
Returns a ISO 8601 HH:mm:ss.SSS formated string of a Duration object
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault());
long millis = duration.toMillis();
return format.format(new Date(millis - TimeZone.getDefault().getRawOffset()));
DurationgetDurationByTimeValues(final long hours, final long minutes, final long seconds)
converts values of time constants to a Duration object..
return Duration.ofHours(hours).plusMinutes(minutes).plusSeconds(seconds);