How to convert Youtube API V3 duration in Java

前端 未结 15 2006
梦如初夏
梦如初夏 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:13

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

提交回复
热议问题