How to convert Youtube API V3 duration in Java

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

    public String pretty(String duration) {
      String time = duration.replace("PT", "");
      String hour = null;
      String minute = null;
      String second = null;
    
      if (time.indexOf("H") > 0) {
        String[] split = time.split("H");
        if (split.length > 0) {
          hour = split[0];
        }
        if (split.length > 1) {
          time = split[1];
        }
      }
    
      if (time.indexOf("M") > 0) {
        String[] split = time.split("M");
        if (split.length > 0) {
          minute = split[0];
        }
        if (split.length > 1) {
          time = split[1];
        }
      }
    
      if (time.indexOf("S") > 0) {
        String[] split = time.split("S");
        if (split.length > 0) {
          second = split[0];
        }
      }
    
      if (TextUtils.isEmpty(hour)) {
        if (TextUtils.isEmpty(minute)) { return "0:" + pad(second, 2, '0'); }
        else { return minute + ":" + pad(second, 2, '0'); }
      }
      else {
        if (TextUtils.isEmpty(minute)) { return hour + ":00:" + pad(second, 2, '0'); }
        else {return hour + ":" + pad(minute, 2, '0') + ":" + pad(second, 2, '0');}
      }
    }
    
    private String pad(String word, int length, char ch) {
      if (TextUtils.isEmpty(word)) { word = ""; }
      return length > word.length() ? pad(ch + word, length, ch) : word;
    }
    

提交回复
热议问题