Question

I would like to convert a number of seconds into ISO_8601/Duration in Java.

http://en.wikipedia.org/wiki/ISO_8601#Durations

Are there any existing methods to do it that are already built in?

Was it helpful?

Solution

Since ISO 8601 allows for the individual fields in a duration string to overflow, you could just prepend "PT" to the number of seconds and append "S":

int secs = 4711;
String iso8601format = "PT" + secs + "S";

This will output "PT4711S", which is equivalent to "PT1H18M31S".

OTHER TIPS

I recommend using the Period object from the JodaTime library. Then you could write a method like so:

public static String secondsAsFormattedString(long seconds) {
     Period period = new Period(1000 * seconds);
     return "PT" + period.getHours() + "H" + period.getMinutes() + "M" + period.getSeconds() + "S";
 }

Duration#ofSeconds

Demo:

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        System.out.println(Duration.ofSeconds(4711));
    }
}

Output:

PT1H18M31S

I second the recommendation of the JodaTime library; but I suggest toString() or Joda's ISOPeriodFormat class since small periods (like 300 seconds) will show as "PT0H5M0S" which although correct, may fail things like (poorly written) ISO certification tests expecting "PT5M".

Period period = new Period(1000 * seconds);

String duration1 = period.toString();
String duration2 = ISOPeriodFormat.standard().print(period);

Although I've never seen period.toString() give an incorrect result, I use ISOPeriodFormat for clarity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top