如何在Java中转换Youtube API V3的视频时长

21

Youtube V3 API使用ISO8601时间格式描述视频的时长,例如"PT1M13S"。现在我想将这个字符串转换为秒数(例如在此情况下为73)。

是否有任何Java库可以帮助我在Java 6下轻松完成此任务?还是我必须自己完成正则表达式任务?

编辑

最终我接受了@Joachim Sauer的答案。

使用Joda的示例代码如下:

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

System.out.println(s.getSeconds());

这是重复的吗?这个问题是关于日期格式的。 - Willy
真的不明白如何使用SimpleDateFormat来获取此情况下的秒数,因为它不是日期格式。谢谢! - Willy
@nhahtdh:这不是重复的问题,因为链接到的问题处理日期字符串,而这是一个持续时间字符串! - Joachim Sauer
15个回答

15

Joda Time是处理任何与时间相关功能的首选库。

对于此特定情况,ISOPeriodFormat.standard() 返回一个 PeriodFormatter 对象,用于解析和格式化该格式。

返回的对象是PeriodJavaDoc)。获取实际秒数的方法是 period.toStandardSeconds().getSeconds(),但我建议您将持续时间视为 Period 对象(方便处理和类型安全)。

编辑:来自未来我的一条注释:这个答案现在已经过时了几年。Java 8 引入了 java.time.Duration,也可以解析此格式而无需外部库。


谢谢!我先看一下。 - Willy

14

Java 8的解决方案:

Duration.parse(duration).getSeconds()

你必须确保你的JAVA_HOME设置为JDK8或者你的IDE配置使用JDK8。我不得不添加Maven插件才能让上述代码在我的IntelliJ IDEA 17中工作。插件URL:http://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin - realPK
3
在Android中,将以下代码添加到gradle文件中:compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }但这只适用于API 26及以上版本,因此目前不建议使用。 - user924

13

我可能会迟到参加派对,但这很简单。虽然可能有更好的方法来实现这一点。持续时间以毫秒为单位。

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;
}

3

这是我的解决方案

public class MyDateFromat{
    public static void main(String args[]){
        String ytdate = "PT1H1M15S";
        String result = ytdate.replace("PT","").replace("H",":").replace("M",":").replace("S","");
        String arr[]=result.split(":");
        String timeString = String.format("%d:%02d:%02d", Integer.parseInt(arr[0]), Integer.parseInt(arr[1]),Integer.parseInt(arr[2]));
        System.out.print(timeString);       
    }
}

如果您想将其转换为秒,它会返回一个H:MM:SS格式的字符串,您可以使用以下方法:

int timeInSedonds = int timeInSecond = Integer.parseInt(arr[0])*3600 + Integer.parseInt(arr[1])*60 +Integer.parseInt(arr[2])

注意:它可能会抛出异常,因此请根据result.split(":")的大小进行处理。

这个问题在stackoverflow上最简单和最好的解决方案 - Karan Sharma
请注意,时间字段可能缺少H、M或S(例如PT35M10S或PT1H30S)。无法保证H、M或S出现在该字段中。 - Angel Koh

1
也许这会帮助那些不想使用任何库而只需要简单函数的人。
String duration="PT1H11M14S";

这是函数:

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;
}

0

我自己做了

让我们试试

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.

public class YouTubeDurationUtils {
    /**
     * 
     * @param duration
     * @return "01:02:30"
     */
    public static String convertYouTubeDuration(String duration) {
        String youtubeDuration = duration; //"PT1H2M30S"; // "PT1M13S";
        Calendar c = new GregorianCalendar();
        try {
            DateFormat df = new SimpleDateFormat("'PT'mm'M'ss'S'");
            Date d = df.parse(youtubeDuration);
            c.setTime(d);
        } catch (ParseException e) {
            try {
                DateFormat df = new SimpleDateFormat("'PT'hh'H'mm'M'ss'S'");
                Date d = df.parse(youtubeDuration);
                c.setTime(d);
            } catch (ParseException e1) {
                try {
                    DateFormat df = new SimpleDateFormat("'PT'ss'S'");
                    Date d = df.parse(youtubeDuration);
                    c.setTime(d);
                } catch (ParseException e2) {
                }
            }
        }
        c.setTimeZone(TimeZone.getDefault());

        String time = "";
        if ( c.get(Calendar.HOUR) > 0 ) {
            if ( String.valueOf(c.get(Calendar.HOUR)).length() == 1 ) {
                time += "0" + c.get(Calendar.HOUR);
            }
            else {
                time += c.get(Calendar.HOUR);
            }
            time += ":";
        }
        // test minute
        if ( String.valueOf(c.get(Calendar.MINUTE)).length() == 1 ) {
            time += "0" + c.get(Calendar.MINUTE);
        }
        else {
            time += c.get(Calendar.MINUTE);
        }
        time += ":";
        // test second
        if ( String.valueOf(c.get(Calendar.SECOND)).length() == 1 ) {
            time += "0" + c.get(Calendar.SECOND);
        }
        else {
            time += c.get(Calendar.SECOND);
        }
        return time ;
    }
}

0

我已经实现了这个方法,到目前为止它运行良好。

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; 

}

0

我已经编写并使用了这种方法来获取实际持续时间。希望这可以帮到你。

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

0

还有另一种冗长的方式来实现相同的功能。

// PT1H9M24S -->  1:09:24
// PT2H1S"   -->  2:00:01
// PT23M2S   -->  23:02
// PT31S     -->  0:31

public String convertDuration(String duration) {
    duration = duration.substring(2);  // del. PT-symbols
    String H, M, S;
    // Get Hours:
    int indOfH = duration.indexOf("H");  // position of H-symbol
    if (indOfH > -1) {  // there is H-symbol
        H = duration.substring(0,indOfH);      // take number for hours
        duration = duration.substring(indOfH); // del. hours
        duration = duration.replace("H","");   // del. H-symbol
    } else {
        H = "";
    }
    // Get Minutes:
    int indOfM = duration.indexOf("M");  // position of M-symbol
    if (indOfM > -1) {  // there is M-symbol
        M = duration.substring(0,indOfM);      // take number for minutes
        duration = duration.substring(indOfM); // del. minutes
        duration = duration.replace("M","");   // del. M-symbol
        // If there was H-symbol and less than 10 minutes
        // then add left "0" to the minutes
        if (H.length() > 0 && M.length() == 1) {
            M = "0" + M;
        }
    } else {
        // If there was H-symbol then set "00" for the minutes
        // otherwise set "0"
        if (H.length() > 0) {
            M = "00";
        } else {
            M = "0";
        }
    }
    // Get Seconds:
    int indOfS = duration.indexOf("S");  // position of S-symbol
    if (indOfS > -1) {  // there is S-symbol
        S = duration.substring(0,indOfS);      // take number for seconds
        duration = duration.substring(indOfS); // del. seconds
        duration = duration.replace("S","");   // del. S-symbol
        if (S.length() == 1) {
            S = "0" + S;
        }
    } else {
        S = "00";
    }
    if (H.length() > 0) {
        return H + ":" +  M + ":" + S;
    } else {
        return M + ":" + S;
    }
}

0

时间已经格式化,所以似乎只需要替换就可以了。

 private String stringForTime(String ytFormattedTime) {
                 return ytFormattedTime
                        .replace("PT","")
                        .replace("H",":")
                        .replace("M",":")
                        .replace("S","");
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接