什么Java库对象封装了一个数字和`TimeUnit`?

The*_*tor 5 java time duration java-8 timeunit

我想传递一个时间数字,TimeUnit它就在.

long number = some number;
TimeUnit timeUnit = some arbitrary time unit
Run Code Online (Sandbox Code Playgroud)

什么可以Object将Java中的时间和时间单元保持在一起?

The*_*tor 7

没有Java库对象封装数字和任意TimeUnit.但是,Java 8中有一个将自身转换为需要的时间单位:

java.time.Duration
Run Code Online (Sandbox Code Playgroud)

持续时间存储提供的数量,然后提供对所有其他时间单位的比较和转换.例如:

// Create duration from nano time
Duration systemTime = Duration.ofNanos(System.nanoTime());

// Create duration from millis time
Duration systemTime = Duration.ofMillis(System.currentTimeMillis());
Run Code Online (Sandbox Code Playgroud)

当然,如果进行加法和减法或其他数学运算,精度只能与当前运算和提供的精度一样好Duration.

/**
* Example that tells if something has reached the required age
* TRUE IF THE current system time is older or equal to the required system time
*/
    // TRUE IF THE FILE HAS NOT WAITED ENOUGH TIME AFTER LAST CREATE/MODIFY
    private boolean isMature() {
        // it is not known whether required age is nanos or millis
        Duration requiredAge = systemTimeWhenMature();
        // so create a duration in whatever time unit you have
        // more precise = possibly better here
        Duration actualAge = Duration.ofNanos(System.nanoTime());
       // if ON or OLDER THAN REQUIRED AGE
       // actualAge - requiredAge  = balance
       // 20 - 21 = -1 (NOT MATURE)
       // 21 - 21 =  0 (OK)
       // 22 - 21 =  1 (OK)
       Duration balance = actualAge.minus(requiredAge);
       if (balance.isNegative()) {
           logger.info("Something not yet expired. Expires in {} millis.", balance.negated());
           return false;
       } else {
           return true;
       }
    }
Run Code Online (Sandbox Code Playgroud)

持续时间中有许多方法可用于转换和处理各个单元中的存储数量.

了解精度如何影响计算非常重要.这通过示例显示了一般精度契约:

    // PICK A NUMBER THAT IS NOT THE SAME WHEN CONVERTED TO A LESSER PRECISION
    long timeNanos = 1234567891011121314L;
    long timeMillis = TimeUnit.MILLISECONDS.convert(timeNanos, TimeUnit.NANOSECONDS);

    // create from milliseconds
    Duration millisAccurate = Duration.ofMillis(timeMillis);
    Duration nanosAccurate = Duration.ofNanos(timeNanos);

    // false because of precision difference
    assertFalse(timeMillis == timeNanos);
    assertFalse(millisAccurate.equals(nanosAccurate));

    // true because same logical precision conversion takes place
    assertTrue(timeMillis - timeNanos <= 0);
    assertTrue(millisAccurate.minus(nanosAccurate).isNegative());

    // timeNanos has greater precision and therefore is > timeMillie
    assertTrue(timeNanos - timeMillis > 0);
    assertTrue(nanosAccurate.minus(millisAccurate).negated().isNegative());
Run Code Online (Sandbox Code Playgroud)

简而言之......我简直不敢相信我花了很长时间才找到它Duration!:)


Loc*_*Loc 1

TimeUnit 只是包含一些时间单位类型的枚举,例如秒,毫秒,...

TimeUnit 不适用于保持时间,但您可以使用 TimeUnit API 将时间单位转换为另一个单位。

我认为你必须创建你的对象来保存时间及其单位。

如果您使用 Java 8。您可以使用一些新的 Date API

http://download.java.net/jdk8/docs/api/java/time/package-summary.html