How to convert Youtube API V3 duration in Java

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

    Here is my solution

    public class MyDateFromat{
        public static void main(String args[]){
            String ytdate = "PT1H1M15S";
            String result = ytdate.replace("PT","").replace("H",":").replace("M",":").replace("S","");
            String arr[]=result.split(":");
            String timeString = String.format("%d:%02d:%02d", Integer.parseInt(arr[0]), Integer.parseInt(arr[1]),Integer.parseInt(arr[2]));
            System.out.print(timeString);       
        }
    }
    

    It will return a string in H:MM:SS format if you want to convert in seconds you can use

    int timeInSedonds = int timeInSecond = Integer.parseInt(arr[0])*3600 + Integer.parseInt(arr[1])*60 +Integer.parseInt(arr[2])
    

    Note: it can throw exception so please handle it based on size of result.split(":");

提交回复
热议问题