How to convert Youtube API V3 duration in Java

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

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

提交回复
热议问题