ISO 8601 Time Interval Parsing in Java

fellahst picture fellahst · Apr 12, 2013 · Viewed 24.1k times · Source

ISO 8601 defines a syntax for representing a time interval.

There are four ways to express a time interval:

  • Start and end, such as "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z"
  • Start and duration, such as "2007-03-01T13:00:00Z/P1Y2M10DT2H30M"
  • Duration and end, such as "P1Y2M10DT2H30M/2008-05-11T15:30:00Z"
  • Duration only, such as "P1Y2M10DT2H30M", with additional context information

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).

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".

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 ?

Answer

Shaun Parker picture Shaun Parker · Nov 24, 2015

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));

Prints Duration in seconds: 3754