mscharhag, Programming and Stuff;

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

Monday, 13 July, 2020

Quick tip: ISO 8601 durations in Java

Many developers know about the interchange formats for dates and times defined by ISO 8601. (For example 2007-08-31T16:47+00:00 which represents 16:47 on August 31, 2007 in UTC)

However, what is not so well-known (at least in my experience), is that this standard also defines a format for durations.

Here are a few examples:

  • P1Y - 1 year
  • P2M4D - 2 months and 4 days
  • P3Y6M4DT12H30M5S - 3 years, 7 months, 4 days, 12 hours, 30 minutes, and 5 seconds

In Java it is quite easy to work with this format because the java.time API can automatically parse it to Duration and Period objects.

Duration is used to work with hours and smaller time units while Period works with dates.

For example:

Duration duration = Duration.parse("PT12H"); // 12 hours
Period period = Period.parse("P3Y6M"); // 3 years and 6 months

We can now work with these instances, for example we can add period to a LocalDate:

LocalDate result = LocalDate.of(2020, 8, 1).plus(period); // 2024-02-01

Leave a reply