将秒转换为T1H15M5S(ISO_8601)

时间:2013-07-29 14:11:19

标签: java time converter duration

我想将数秒转换为ISO中的ISO_8601 / Duration。

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

是否有现成的方法可以内置?

4 个答案:

答案 0 :(得分:2)

由于ISO 8601允许持续时间字符串中的各个字段溢出,您可以将“PT”添加到秒数并附加“S”:

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

这将输出“PT4711S”,相当于“PT1H18M31S”。

答案 1 :(得分:2)

我建议使用JodaTime库中的Period对象。然后你可以写一个像这样的方法:

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

答案 2 :(得分:1)

Duration#ofSeconds

演示:

import java.time.Duration;

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

输出:

PT1H18M31S

答案 3 :(得分:0)

我第二次推荐JodaTime库;但我建议使用String()或Joda的ISOPeriodFormat类,因为小周期(如300秒)将显示为" PT0H5M0S"虽然这是正确的,可能会失败像(写得不好)ISO认证考试期待" PT5M"。

Period period = new Period(1000 * seconds);

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

虽然我从未见过period.toString()给出错误的结果,但为了清晰起见,我使用了ISOPeriodFormat。