How to convert Youtube API V3 duration in Java

前端 未结 15 2037
梦如初夏
梦如初夏 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 03:47

    In case you can be pretty sure about the validity of the input and can't use regex, I use this code (returns in miliseconds):

    Integer parseYTDuration(char[] dStr) {
        Integer d = 0;
    
        for (int i = 0; i < dStr.length; i++) {
            if (Character.isDigit(dStr[i])) {
                String digitStr = "";
                digitStr += dStr[i];
                i++;
                while (Character.isDigit(dStr[i])) {
                    digitStr += dStr[i];
                    i++;
                }
    
                Integer digit = Integer.valueOf(digitStr);
    
                if (dStr[i] == 'H')
                    d += digit * 3600;
                else if (dStr[i] == 'M')
                    d += digit * 60;
                else
                    d += digit;
            }
        }
    
        return d * 1000;
    }
    

提交回复
热议问题