我正在将一些签名从f(long dur, TimeUnit timeUnit)
迁移到f(Duration duration)
,并希望用后者实现前者。
由于使用的是Java 8,我找不到任何API可以轻松地将long
+TU
转换为Duration
。唯一想到的办法就是做一些难看的事情,比如:
static Duration convert(long dur, TimeUnit timeUnit) {
switch (timeUnit) {
case DAYS:
return Duration.ofDays(dur);
case HOURS:
/* alternative, but (again) I don't have an easy conversion from TimeUnit -> ChronoUnit */
return Duration.of(dur, ChronoUnit.HOURS);
case ..... /* and so on */
}
}
或者我错过了一些API?
toChronoUnit
是从9开始的。 - Adam KotwasinskiTimeUnit
和ChronoUnit
之间的约定是在Java 9中引入的。在Java 8中,我们无法仅使用内置功能将一个转换为另一个,也许有一些第三方库可以简化这个过程。 - Alexander IvanchenkoTimeUnit
到ChronoUnit
的转换很简单,JDK实现非常干净。在Java 8中,我不会为这个简单的转换引入依赖项,而是会编写一个基于JDK源代码的静态实用程序方法(我将其粘贴到我的答案中)。 - Paul