Java 中的 ISO 8601 时间间隔解析 [英] ISO 8601 Time Interval Parsing in Java

查看:44
本文介绍了Java 中的 ISO 8601 时间间隔解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ISO 8601 定义了表示时间间隔的语法.

ISO 8601 defines a syntax for representing a time interval.

时间间隔有四种表示方式:

There are four ways to express a time interval:

  • 开始和结束,例如2007-03-01T13:00:00Z/2008-05-11T15:30:00Z"
  • 开始和持续时间,例如2007-03-01T13:00:00Z/P1Y2M10DT2H30M"
  • 持续时间和结束时间,例如P1Y2M10DT2H30M/2008-05-11T15:30:00Z"
  • 仅持续时间,例如P1Y2M10DT2H30M",以及其他上下文信息

如果结束值中缺少任何元素,则假定它们与包含时区的起始值相同.该标准的这一特性允许对时间间隔进行简明的表示.例如,包含开始和结束时间的两小时会议的日期可以简单地显示为2007-12-14T13:30/15:30",其中/15:30"意味着/2007-12-14T15:30"(与开始日期相同),或每月计费周期的开始和结束日期为2008-02-15/03-14",其中/03-14"表示/2008-03"-14"(与开始的年份相同).

If any elements are missing from the end value, they are assumed to be the same as for the start value including the time zone. This feature of the standard allows for concise representations of time intervals. For example, the date of a two-hour meeting including the start and finish times could be simply shown as "2007-12-14T13:30/15:30", where "/15:30" implies "/2007-12-14T15:30" (the same date as the start), or the beginning and end dates of a monthly billing period as "2008-02-15/03-14", where "/03-14" implies "/2008-03-14" (the same year as the start).

此外,重复区间是通过在区间表达式的开头添加R[n]/"形成的,其中R用作字母本身,[n]被重复的次数代替.省略 [n] 的值意味着无限次数的重复.因此,要从2008-03-01T13:00:00Z"开始重复P1Y2M10DT2H30M"的间隔五次,请使用R5/2008-03-01T13:00:00Z/P1Y2M10DT2H30M".

In addition, repeating intervals are formed by adding "R[n]/" to the beginning of an interval expression, where R is used as the letter itself and [n] is replaced by the number of repetitions. Leaving out the value for [n] means an unbounded number of repetitions. So, to repeat the interval of "P1Y2M10DT2H30M" five times starting at "2008-03-01T13:00:00Z", use "R5/2008-03-01T13:00:00Z/P1Y2M10DT2H30M".

我正在寻找一个好的 Java 解析器(如果可能与 Joda-Time 库兼容)来解析这个语法.任何指向一个好的库的指针?

I am looking for a good Java parser (if possible compatible with the Joda-Time library) to parse this syntax. Any pointers to a good library ?

推荐答案

java.time

Java 8 中内置的 java.time 框架后来有一个持续时间.parse 用于解析 ISO 8601 格式的持续时间的方法:

java.time

The java.time framework built into Java 8 and later has a Duration.parse method for parsing an ISO 8601 formatted duration:

java.time.Duration d = java.time.Duration.parse("PT1H2M34S");
System.out.println("Duration in seconds: " + d.get(java.time.temporal.ChronoUnit.SECONDS));

打印持续时间(以秒为单位):3754

这篇关于Java 中的 ISO 8601 时间间隔解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆