IIUC java.time 应该结束多个日期库和相关问题,并提供一些好的和标准化的东西。所以得知 java.time.Duration 违反了 iso8601 标准,我有点震惊。虽然应该可以解析:P2Y1DT1S
,因为它按标准有效,java.time.Duration
最多只能解析几天(因此您必须通过 P731DT1S
和 java.time.Period
根本无法做到这一点,因为它不允许时间部分。
问题:
为什么?是否有正当理由不根据规范进行区间解析?我忽略了什么?
或者是否有一些现成的类可以解析 ISO8601?
最佳答案
嗯,解析这样一个字符串意味着它会产生一个对象,该对象支持同时出现这两个概念——一种 PeriodDuration
。但是 Java 中没有,它的基本原理是 JodaStephen 的 explained here:
Note that a
Duration
contains an amount of seconds, not separate amounts of seconds, minutes and hours. The amount of seconds can exceed 24 hours, thus aDuration
can represent a "day". But it is a fixed 24 hours day. By contrast, the representation of a "day inPeriod
is descriptive and takes into account DST. The state of aPeriod
is formed from three separate fields - days, months and years.Bear in mind that "The customer occupied the hotel room for 2 days and seventeen and a half hours, P2DT17H30M" has the possibility to be complicated by DST cutovers. Using
Period
andDuration
separately things are clear -Period
is affected by DST cutovers andDuration
is not.
(强调我的。)
简而言之,这两个概念处理 DST 的方式不同,将两者结合起来会使事情变得复杂。
关于你的第二个问题,this answer建议使用org.threeten.extra.PeriodDuration
库提供的ThreeTen-Extra类。
关于java.time.Duration 实现与 ISO8601 标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73321462/