java.time.Duration 实现与 ISO8601 标准

标签 java

IIUC java.time 应该结束多个日期库和相关问题,并提供一些好的和标准化的东西。所以得知 java.time.Duration 违反了 iso8601 标准,我有点震惊。虽然应该可以解析:P2Y1DT1S,因为它按标准有效,java.time.Duration 最多只能解析几天(因此您必须通过 P731DT1Sjava.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 a Duration can represent a "day". But it is a fixed 24 hours day. By contrast, the representation of a "day in Period is descriptive and takes into account DST. The state of a Period 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 and Duration separately things are clear - Period is affected by DST cutovers and Duration is not.

(强调我的。)

简而言之,这两个概念处理 DST 的方式不同,将两者结合起来会使事情变得复杂。


关于你的第二个问题,this answer建议使用org.threeten.extra.PeriodDuration库提供的ThreeTen-Extra类。

关于java.time.Duration 实现与 ISO8601 标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73321462/

相关文章:

java - WeakHashMap 随机清除

java - 如何检查和匹配 arraylist 元素的可能组合

java - 估计 memcached 中 Java 对象的大小

java - Android Retrofit 的烦恼

java - Servlet 在访问网络驱动器时抛出文件未找到 excp

java - 使用正则表达式从长字符串中捕获特定位置值

java - 为什么 Math.round() 为 NaN 参数返回 0?

java - java.library.path 和 classpath 之间有什么关系

java - mybatis 为过程调用返回原始类型

java - Eclipse kepler - 禁用 javascript 验证