gpt4 book ai didi

java - 如何将 Time4J 持续时间转换为分钟数?

转载 作者:行者123 更新时间:2023-12-04 17:16:19 24 4
gpt4 key购买 nike

如何转换 Time4J Duration<ClockUnit>到多少分钟?我可以截断任何秒,我只想要整分钟。几个简单的例子可能解释得最好:

  • 对于 Duration.of(1, ClockUnit.HOURS)我想要 60。
  • 对于 Duration.of(34, ClockUnit.SECONDS)我想要 0。

没有toMinutes方法(就像 java.time.Duration 中的那样)。我玩了一个 Normalizer , getTotalLength方法和流操作并获得了 6 行解决方案,但肯定有更简单的方法吗?

小时和秒的解决方案也可能很有趣,但我希望它们或多或少是对分钟解决方案的微不足道的修改。

链接: Documentation of net.time4j.Duration

最佳答案

标准化为分钟并使用 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 Tutorial: Element centric approach

关于java - 如何将 Time4J 持续时间转换为分钟数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68652953/

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