“PT”前缀在 Duration 中代表什么?

新手上路,请多包涵

我正在尝试使用 Duration 类而不是 long 。它具有优越的文字语法。我喜欢它的灵活性,尽管它看起来很奇怪。

“PT10S”表示10秒,接受“10秒”有什么问题?!好的没关系。

我很好奇为什么选择了 PT 前缀(而不是“DU”,例如)以及为什么在这里使用任何前缀都比什么都没有更好?

原文由 Daniil Iaitskov 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2k
2 个回答

可以在 Jesper 链接的页面上找到( ISO-8601 - 数据元素和交换格式 - 信息交换 - 日期和时间的表示

 P is the duration designator (for period) placed at the start of the duration representation.
Y is the year designator that follows the value for the number of years.
M is the month designator that follows the value for the number of months.
W is the week designator that follows the value for the number of weeks.
D is the day designator that follows the value for the number of days.
T is the time designator that precedes the time components of the representation.

所以 P 的意思是“期间”,因为没有日期组件,所以它只有一个“时间”。

您可以将其解释为“时间段”

为什么选择这个,你必须问编写标准的 ISO 成员,但我猜它更容易解析。 (简短而明确)

时间组件的详细信息是:

 H is the hour designator that follows the value for the number of hours.
M is the minute designator that follows the value for the number of minutes.
S is the second designator that follows the value for the number of seconds.

PT20S 的值解析为:

  • 时期
  • 时间
  • 20

因此,持续时间为 20 秒。

更多示例可以在 javadoc 中找到: https ://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-

原文由 Rob Audenaerde 发布,翻译遵循 CC BY-SA 4.0 许可协议

Java 在一段时间内采用了 ISO 8601 标准格式的一个子集。所以“为什么”就是为什么标准是这样写的,这是一个猜谜游戏。我的做法是:

  • P 选择了时间段,以便您可以将持续时间与日期和/或时间区分开来。特别是因为句点也可以用与本地日期时间相同的格式编写,例如 P0003-06-04T12:30:05 3 年 6 个月 4 天 12 小时 30 分 5 秒, P 可根据需要加以区分。 P 还提供了一点点但快速方便的验证,以防您碰巧在预期持续时间的地方传递完全不同的字符串。是的, PT10S 看起来很奇怪,但是一旦你习惯了它,你就会立即将它识别为一个持续时间,这很实用。
  • T 选择日期部分和时间部分之间的时间有两个原因:
    • 为了与在同一位置具有 T 的日期时间字符串保持一致,例如 2018-07-04T15:00 2018 年 7 月 4 日 15:00。
    • 为了消除歧义 M 几个月或几分钟: P3M 明确意味着3个月而 PT3M 分钟

原文由 Ole V.V. 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题