3

How do I convert a Time4J Duration<ClockUnit> to a number of minutes? I’m fine with truncating any seconds, I just want the whole minutes. A couple of simple examples probably explain the best:

  • For Duration.of(1, ClockUnit.HOURS) I want 60.
  • For Duration.of(34, ClockUnit.SECONDS) I want 0.

There isn’t any toMinutes method (like there is in java.time.Duration). I played around with a Normalizer, the getTotalLength method and a stream operation and got a 6 lines solution to work, but surely there is a simpler way?

The solutions for hours and seconds could also be interesting, but I expect them to be more or less trivial modifications of the solution for minutes.

Link: Documentation of net.time4j.Duration

4

1 回答 1

1

标准化为分钟并使用 getPartialAmount()

我们确实需要规范器。我们从ClockUnit.only(). 然后getPartialAmount()照顾其余的。

    List<Duration<ClockUnit>> durations = Arrays.asList(
            Duration.of(1, ClockUnit.HOURS),
            Duration.of(34, ClockUnit.SECONDS));
    
    for (Duration<ClockUnit> dur : durations) {
        long minutes = dur.with(ClockUnit.MINUTES.only())
                .getPartialAmount(ClockUnit.MINUTES);
        System.out.format("%s = %d minutes%n", dur, minutes);
    }

输出:

PT1H = 60 minutes
PT34S = 0 minutes

正如教程(底部的链接)中所解释的,Time4J 主要围绕时间元素(或字段)设计,例如年、月,是的,分钟。所以在代码中,我们首先需要将持续时间转换为只有分钟的持续时间,之后我们可以取出分钟元素的值——现在是持续时间中唯一的元素(在 14 秒的情况下,甚至没有任何分钟元素,但getPartialAmount()在这种情况下明智地返回 0)。

我们显然应该将转换包装成一个方法:

private static final long durationToNumber(Duration<ClockUnit> dur, ClockUnit unit) {
    return dur.with(unit.only()).getPartialAmount(unit);
}

作为奖励,此方法使我们可以免费转换为小时或秒:

    for (Duration<ClockUnit> dur : durations) {
        long hours = durationToNumber(dur, ClockUnit.HOURS);
        long seconds = durationToNumber(dur, ClockUnit.SECONDS);
        System.out.format("%s = %d hours or %d seconds%n", dur, hours, seconds);
    }
PT1H = 1 hours or 3600 seconds
PT34S = 0 hours or 34 seconds

关联

Time4J 教程:以元素为中心的方法

于 2021-08-04T14:31:27.033 回答