gpt4 book ai didi

java - 将 time4j Duration 从 P365D 转换为 P1Y 等

转载 作者:行者123 更新时间:2023-11-29 04:09:03 25 4
gpt4 key购买 nike

Instant i1 = Instant.now();
Instant i2 = Instant.now().plusSeconds(60 * 60 * 24 * 365);
Duration<IsoUnit> dur = Duration.from((TemporalAmount) java.time.Duration.between(i1, i2));
System.out.println(dur);

此代码打印 P365D,有没有办法让单位填满下一个更大的单位,所以这变成 P1Y,如果我喜欢 P334D 到 P11M 等等?

time4j版本是4.38

最佳答案

其他评论和答案说一年并不总是等于 365 天是完全正确的。

Time4J 方法 net.time4j.Duration.from(TemporalAmount)使用 STD_PERIOD 作为标准化器返回标准化持续时间。这个标准化器的文档说:

Normalizes the duration items on the base of 1 year = 12 months and 1 day = 24 hours and 1 hour = 60 minutes and 1 minute = 60 seconds - without converting days to months.

因此,当您从以秒为单位定义的时间量开始时,您只能期望结果以天为单位。

如果您仍然想要一年,那么我建议您首先使用适当的时区将您的瞬间转换为日历日期。但是在闰年,你的代码仍然会产生 365 天,而不是在第二个瞬间添加 60 * 60 * 24 * 365 秒后的一年。所以你添加的秒数也是有缺陷的,因为它是基于错误的假设。

边注:

如果你想要相反的方式,即一年有多少秒,那么你可以使用如下代码

Moment m1 = Moment.nowInSystemTime();
Moment m2 = m1.toZonalTimestamp(ZonalOffset.UTC).plus(1, CalendarUnit.YEARS).atUTC();
long seconds = SI.SECONDS.between(m1, m2); // = 366 days in seconds if applied on date 2019-05-22!

随着 Time4J 的 future 版本和 2019 年底可能出现的闰秒,代码甚至可能产生额外的一秒。

无论如何,我建议您将 Time4J 更新到 v5.4 并考虑以下映射:

java.time.Instant as input => net.time4j.MachineTime.from(...)
java.time.LocalDateTime/net.time4j.PlainTimestamp => net.time4j.Duration.from(...)

因此,如果您真的希望在打印持续时间中输出尽可能多的年并且您有瞬间/时刻,那么在创建适当的持续时间对象之前首先转换为 LocalDateTime/PlainTimestamp(使用时区或偏移量)。

2019-05-25 更新:

通过“模糊”持续时间可以使用版本 v5.4(或更高版本)的另一种方式。您可以通过应用近似值来归一化您获得的持续时间。示例:

    Duration<IsoUnit> d = Duration.of(60 * 60 * 24 * 365, ClockUnit.SECONDS);
d = d.with(Duration.approximateMaxUnitOnly());
System.out.println(d); // P1Y

由于这种规范化的性质,您无法期望得到准确的结果。

关于java - 将 time4j Duration<IsoUnit> 从 P365D 转换为 P1Y 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56240919/

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