Home » Java » Core Java » Quick tip: ISO 8601 durations in Java

About Michael Scharhag

Michael Scharhag
Michael Scharhag is a Java Developer, Blogger and technology enthusiast. Particularly interested in Java related technologies including Java EE, Spring, Groovy and Grails.

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:

1
2
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:

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

Published on Java Code Geeks with permission by Michael Scharhag, partner at our JCG program. See the original article here: Quick tip: ISO 8601 durations in Java

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments