5

我想传递一个时间数字,TimeUnit它就在里面。

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

ObjectJava 库中什么可以同时保存时间和时间单位?

4

3 回答 3

8

没有封装数字和任意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;
       }
    }

Duration 中还有更多方法可用于转换和处理各种单位的存储数量。

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

    // 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!:)

于 2013-12-08T02:54:49.527 回答
1

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

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

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

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

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

于 2013-12-08T00:05:18.373 回答
1

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

于 2013-12-08T00:07:08.503 回答