Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Youtube API V3 duration in Java

The Youtube V3 API uses ISO8601 time format to describe the duration of videos. Something likes "PT1M13S". And now I want to convert the string to the number of seconds (for example 73 in this case).

Is there any Java library can help me easily do the task under Java 6? Or I have to do the regex task by myself?

Edit

Finally I accept the answer from @Joachim Sauer

The sample code with Joda is as below.

PeriodFormatter formatter = ISOPeriodFormat.standard();
Period p = formatter.parsePeriod("PT1H1M13S");
Seconds s = p.toStandardSeconds();

System.out.println(s.getSeconds());
like image 846
Willy Avatar asked May 29 '13 11:05

Willy


3 Answers

Joda Time is the go-to library for time-related functions of any kind.

For this specific case ISOPeriodFormat.standard() returns a PeriodFormatter that can parse and format that format.

The resulting object is a Period (JavaDoc). Getting the actual number of seconds would then be period.toStandardSeconds().getSeconds(), but I suggest you just handle the duration as a Period object (for ease of handling and for type safety).

Edit: a note from future me: this answer is several years old now. Java 8 brought java.time.Duration along which can also parse this format and doesn't require an external library.

like image 65
Joachim Sauer Avatar answered Nov 03 '22 12:11

Joachim Sauer


Solution in Java 8:

Duration.parse(duration).getSeconds()
like image 31
Kamil Avatar answered Nov 03 '22 12:11

Kamil


I may be late for the party, it's actually very simple. Although there may be better ways of doing this. duration is in milliseconds.

public long getDuration() {
    String time = "PT15H12M46S".substring(2);
    long duration = 0L;
    Object[][] indexs = new Object[][]{{"H", 3600}, {"M", 60}, {"S", 1}};
    for(int i = 0; i < indexs.length; i++) {
        int index = time.indexOf((String) indexs[i][0]);
        if(index != -1) {
            String value = time.substring(0, index);
            duration += Integer.parseInt(value) * (int) indexs[i][1] * 1000;
            time = time.substring(value.length() + 1);
        }
    }
    return duration;
}
like image 13
Answer Avatar answered Nov 03 '22 12:11

Answer