How to convert Youtube API V3 duration in Java

2019-03-18 02:18发布

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());

13条回答
乱世女痞
2楼-- · 2019-03-18 02:25

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.

查看更多
够拽才男人
3楼-- · 2019-03-18 02:26

May be this would help some one who don't want any library but a simple function,

String duration="PT1H11M14S";

This is the function,

private String getTimeFromString(String duration) {
    // TODO Auto-generated method stub
    String time = "";
    boolean hourexists = false, minutesexists = false, secondsexists = false;
    if (duration.contains("H"))
        hourexists = true;
    if (duration.contains("M"))
        minutesexists = true;
    if (duration.contains("S"))
        secondsexists = true;
    if (hourexists) {
        String hour = "";
        hour = duration.substring(duration.indexOf("T") + 1,
                duration.indexOf("H"));
        if (hour.length() == 1)
            hour = "0" + hour;
        time += hour + ":";
    }
    if (minutesexists) {
        String minutes = "";
        if (hourexists)
            minutes = duration.substring(duration.indexOf("H") + 1,
                    duration.indexOf("M"));
        else
            minutes = duration.substring(duration.indexOf("T") + 1,
                    duration.indexOf("M"));
        if (minutes.length() == 1)
            minutes = "0" + minutes;
        time += minutes + ":";
    } else {
        time += "00:";
    }
    if (secondsexists) {
        String seconds = "";
        if (hourexists) {
            if (minutesexists)
                seconds = duration.substring(duration.indexOf("M") + 1,
                        duration.indexOf("S"));
            else
                seconds = duration.substring(duration.indexOf("H") + 1,
                        duration.indexOf("S"));
        } else if (minutesexists)
            seconds = duration.substring(duration.indexOf("M") + 1,
                    duration.indexOf("S"));
        else
            seconds = duration.substring(duration.indexOf("T") + 1,
                    duration.indexOf("S"));
        if (seconds.length() == 1)
            seconds = "0" + seconds;
        time += seconds;
    }
    return time;
}
查看更多
叼着烟拽天下
4楼-- · 2019-03-18 02:28

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;
}
查看更多
爷的心禁止访问
5楼-- · 2019-03-18 02:29

I have written and used this method to get the actual duration. Hope this helps.

private String parseDuration(String duration) {
    duration = duration.contains("PT") ? duration.replace("PT", "") : duration;
    duration = duration.contains("S") ? duration.replace("S", "") : duration;
    duration = duration.contains("H") ? duration.replace("H", ":") : duration;
    duration = duration.contains("M") ? duration.replace("M", ":") : duration;
    String[] split = duration.split(":");
    for(int i = 0; i< split.length; i++){
        String item = split[i];
        split[i] = item.length() <= 1 ? "0"+item : item;
    }
    return TextUtils.join(":", split);
}
查看更多
老娘就宠你
6楼-- · 2019-03-18 02:32

Using this website:

// URL that generated this code:
// http://txt2re.com/index-java.php3?s=PT1M13S&6&3&18&20&-19&-21 

import java.util.regex.*;

class Main
{
  public static void main(String[] args)
  {
    String txt="PT1M13S";

    String re1="(P)";   // Any Single Character 1
    String re2="(T)";   // Any Single Character 2
    String re3="(\\d+)";    // Integer Number 1
    String re4="(M)";   // Any Single Character 3
    String re5="(\\d+)";    // Integer Number 2
    String re6="(S)";   // Any Single Character 4

    Pattern p = Pattern.compile(re1+re2+re3+re4+re5+re6,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = p.matcher(txt);
    if (m.find())
    {
        String c1=m.group(1);
        String c2=m.group(2);
        String minutes=m.group(3); // Minutes are here
        String c3=m.group(4);
        String seconds=m.group(5); // Seconds are here
        String c4=m.group(6);
        System.out.print("("+c1.toString()+")"+"("+c2.toString()+")"+"("+minutes.toString()+")"+"("+c3.toString()+")"+"("+seconds.toString()+")"+"("+c4.toString()+")"+"\n");

        int totalSeconds = Integer.parseInt(minutes) * 60 + Integer.parseInt(seconds);
    }
  }
}
查看更多
狗以群分
7楼-- · 2019-03-18 02:37

I've implemented this method and it has worked so far.

private String timeHumanReadable (String youtubeTimeFormat) {
// Gets a PThhHmmMssS time and returns a hh:mm:ss time

    String
            temp = "",
            hour = "",
            minute = "",
            second = "",
            returnString;

    // Starts in position 2 to ignore P and T characters
    for (int i = 2; i < youtubeTimeFormat.length(); ++ i)
    {
        // Put current char in c
        char c = youtubeTimeFormat.charAt(i);

        // Put number in temp
        if (c >= '0' && c <= '9')
            temp = temp + c;
        else
        {
            // Test char after number
            switch (c)
            {
                case 'H' : // Deal with hours
                    // Puts a zero in the left if only one digit is found
                    if (temp.length() == 1) temp = "0" + temp;

                    // This is hours
                    hour = temp;

                    break;

                case 'M' : // Deal with minutes
                    // Puts a zero in the left if only one digit is found
                    if (temp.length() == 1) temp = "0" + temp;

                    // This is minutes
                    minute = temp;

                    break;

                case  'S': // Deal with seconds
                    // Puts a zero in the left if only one digit is found
                    if (temp.length() == 1) temp = "0" + temp;

                    // This is seconds
                    second = temp;

                    break;

            } // switch (c)

            // Restarts temp for the eventual next number
            temp = "";

        } // else

    } // for

    if (hour == "" && minute == "") // Only seconds
        returnString = second;
    else {
        if (hour == "") // Minutes and seconds
            returnString = minute + ":" + second;
        else // Hours, minutes and seconds
            returnString = hour + ":" + minute + ":" + second;
    }

    // Returns a string in hh:mm:ss format
    return returnString; 

}
查看更多
登录 后发表回答