gpt4 book ai didi

java - 什么 Java 库对象封装了数字和 `TimeUnit`?

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:36 25 4
gpt4 key购买 nike

我想传递一个时间数字和它所在的 TimeUnit

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

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

最佳答案

没有封装数字和任意TimeUnit 的Java 库对象。然而,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! :)

关于java - 什么 Java 库对象封装了数字和 `TimeUnit`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20448228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com