How to convert Youtube API V3 duration in Java

前端 未结 15 2000
梦如初夏
梦如初夏 2021-02-07 03:39

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

相关标签:
15条回答
  • 2021-02-07 04:04

    You can use the standart SimpleDateFormat to parse the String to a Date and process it from there:

    DateFormat df = new SimpleDateFormat("'PT'mm'M'ss'S'");
    String youtubeDuration = "PT1M13S";
    Date d = df.parse(youtubeDuration);
    Calendar c = new GregorianCalendar();
    c.setTime(d);
    c.setTimeZone(TimeZone.getDefault());
    System.out.println(c.get(Calendar.MINUTE));
    System.out.println(c.get(Calendar.SECOND));
    
    0 讨论(0)
  • 2021-02-07 04:07

    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;
    }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2021-02-07 04:08

    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.

    0 讨论(0)
  • 2021-02-07 04:08

    I did by myself

    Let's try

    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 讨论(0)
  • 2021-02-07 04:08

    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);
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题