Convert seconds to T1H15M5S (ISO_8601)

I would like to convert a few seconds to ISO_8601 / Duration in Java.

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

Are there already existing methods that are already built-in?

+4
source share
3 answers

Since ISO 8601 allows you to overflow individual fields in a duration line, you can simply add "CT" to the number of seconds and add "S":

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

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

+2
source

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

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

Secondly, the recommendation of the JodaTime library; but I suggest toString () or the Joda ISOPeriodFormat class, as short periods (for example, 300 seconds) will display as “PT0H5M0S”, which, although correct, can disable things like (poorly written) ISO certification tests, awaiting "PT5M".

 Period period = new Period(1000 * seconds); String duration1 = period.toString(); String duration2 = ISOPeriodFormat.standard().print(period); 

Although I have never seen period.toString () give the wrong result, I use ISOPeriodFormat for clarity.

0
source

Source: https://habr.com/ru/post/1494077/


All Articles