在Java中截断持续时间

在Java中截断持续时间,java,truncate,duration,truncation,Java,Truncate,Duration,Truncation,当捕获经过的时间时,我只关心整秒的分辨率 如何从一个对象中删除小数秒 java.time框架中的其他类提供了truncatedTo方法。但是我在Java 9和更高版本上没有看到 为java 8中首次出现的java.time类带来了一些小功能和错误修复 这些特性之一是添加一个方法,类似于在其他类上看到的此类方法。传递一个(接口的实现)来指定要截断的内容的粒度 Duration d = myDuration.truncatedTo( ChronoUnit.SECONDS ) ; 爪哇8 如果您正在

当捕获经过的时间时,我只关心整秒的分辨率

如何从一个对象中删除小数秒

java.time框架中的其他类提供了
truncatedTo
方法。但是我在Java 9和更高版本上没有看到 为java 8中首次出现的java.time类带来了一些小功能和错误修复

这些特性之一是添加一个方法,类似于在其他类上看到的此类方法。传递一个(接口的实现)来指定要截断的内容的粒度

Duration d = myDuration.truncatedTo( ChronoUnit.SECONDS ) ;
爪哇8 如果您正在使用Java 9、10、11或更高版本,并且还不能移动到Java 9、10、11或更高版本,那么请自己计算截断

调用在Java 8版本的上找到的方法。获取
Duration
对象上的纳秒数,然后减去该纳秒数

Duration d = myDuration.minusNanos( myDuration.getNano() ) ;
time类使用该模式。因此,您可以在不改变(“变异”)原始对象的情况下返回一个新对象。

我喜欢。我知道这不是您所要求的,但是我想为Java8提供一个或两个选项,用于我们希望截断为秒以外的单位的情况

如果我们在编写代码时知道单位,我们可以结合
toXx
ofXx
方法来形成截断的持续时间:

    Duration d = Duration.ofMillis(myDuration.toMillis());
    Duration d = Duration.ofSeconds(myDuration.toSeconds());
    Duration d = Duration.ofMinutes(myDuration.toMinutes());
    Duration d = Duration.ofHours(myDuration.toHours());
    Duration d = Duration.ofDays(myDuration.toDays());
如果单位是可变的,我们可以调整您提到的Java 9方法实现中的代码,
truncatedTo

    Duration d;
    if (unit.equals(ChronoUnit.SECONDS) 
            && (myDuration.getSeconds() >= 0 || myDuration.getNano() == 0)) {
        d = Duration.ofSeconds(myDuration.getSeconds());
    } else if (unit == ChronoUnit.NANOS) {
        d = myDuration;
    }
    Duration unitDur = unit.getDuration();
    if (unitDur.getSeconds() > TimeUnit.DAYS.toSeconds(1)) {
        throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation");
    }
    long dur = unitDur.toNanos();
    if ((TimeUnit.DAYS.toNanos(1) % dur) != 0) {
        throw new UnsupportedTemporalTypeException("Unit must divide into a standard day without remainder");
    }
    long nod = (myDuration.getSeconds() % TimeUnit.DAYS.toSeconds(1)) * TimeUnit.SECONDS.toNanos(1)
            + myDuration.getNano();
    long result = (nod / dur) * dur;
    d = myDuration.plusNanos(result - nod);

最初的方法使用了
Duration
类中的一些私有内容,因此需要进行一些更改。代码仅接受
ChronoUnit
单位,不接受其他
TemporalUnit
s。我还没有考虑过推广它有多难。

亲爱的下层选民,请在投票时留下批评。