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

时间:2013-12-07 23:57:32

标签: java time duration java-8 timeunit

我想传递一个时间号,而TimeUnit就是。

long number = some number;
TimeUnit timeUnit = some arbitrary time unit

什么可以在Java库中保存一个Object中的time和timeUnit?

3 个答案:

答案 0 :(得分:7)

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

java.time.Duration

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

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

// Create duration from millis time
Duration systemTime = Duration.ofMillis(System.currentTimeMillis());

当然,如果进行加法和减法或其他数学运算,精度只能与当前操作和提供的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;
       }
    }

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

了解精度如何影响计算非常重要。这显示了 一般精确契约的例子:

    // 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());

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

答案 1 :(得分:1)

TimeUnit只是枚举持有一些时间单位类型,如秒,毫秒,......

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

我认为你必须创建你的对象以保持时间和单位。

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

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

答案 2 :(得分:1)

在Joda-Time中有一个Interval,但是如果你只想使用包含JRE的对象类型,你需要创建一个Java Bean(可能称之为Interval)。