Java TimeUnit Convert durationToMillis(final long val, final TimeUnit unit)

Here you can find the source of durationToMillis(final long val, final TimeUnit unit)

Description

Converts the given duration (interval value plus unit) to milliseconds, ensuring that any given value greater than zero converts to at least one millisecond to avoid a zero millisecond result, since Object.wait(0) waits forever.

License

Open Source License

Exception

Parameter Description
IllegalArgumentException if the duration argument is illegal.Thrown via API setter methods such as Transaction.setLockTimeout.

Declaration

public static int durationToMillis(final long val, final TimeUnit unit) 

Method Source Code

//package com.java2s;
/*-//from  w  ww  .j  ava  2  s .co m
 * See the file LICENSE for redistribution information.
 *
 * Copyright (c) 2002-2010 Oracle.  All rights reserved.
 *
 */

import java.util.concurrent.TimeUnit;

public class Main {
    /**
     * Converts the given duration (interval value plus unit) to milliseconds,
     * ensuring that any given value greater than zero converts to at least one
     * millisecond to avoid a zero millisecond result, since Object.wait(0)
     * waits forever.
     *
     * @throws IllegalArgumentException if the duration argument is illegal.
     * Thrown via API setter methods such as Transaction.setLockTimeout.
     */
    public static int durationToMillis(final long val, final TimeUnit unit) {
        if (val == 0) {
            /* Allow zero duration with null unit. */
            return 0;
        }
        if (unit == null) {
            throw new IllegalArgumentException(
                    "Duration TimeUnit argument may not be null if interval " + "is non-zero");
        }
        if (val < 0) {
            throw new IllegalArgumentException("Duration argument may not be negative: " + val);
        }
        final long newVal = unit.toMillis(val);
        if (newVal == 0) {
            /* Input val is positive, so return at least one. */
            return 1;
        }
        if (newVal > Integer.MAX_VALUE) {
            throw new IllegalArgumentException(
                    "Duration argument may not be greater than " + "Integer.MAX_VALUE milliseconds: " + newVal);
        }
        return (int) newVal;
    }
}

Related

  1. convertTo(long a, TimeUnit from, TimeUnit to)
  2. convertToDouble(long fromTime, TimeUnit fromTimeUnit, TimeUnit toTimeUnit)
  3. convertToMillis(long waitTime, TimeUnit timeUnit)
  4. convertToMilliseconds(TimeUnit timeUnit, long seed)
  5. convertToSecond(int interval, TimeUnit unit)
  6. getDateRelativeToNow(TimeUnit timeUnit, long amount)
  7. getRemainingTimeToday(final TimeUnit timeUnit)
  8. hoursToUnit(double hours, TimeUnit destinationUnit)
  9. millisecondsTo(long milliseconds, final TimeUnit timeUnit)