Search code examples
javaandroidjsondate-format

How to properly format a Youtube video duration in Java (android) taken from Youtube API


We have this call in android:

https://www.googleapis.com/youtube/v3/videos?id=7nwwdhZzVro&part=contentDetails,statistics&key=YOUR_KEY

which gives the following result:

{
"kind": "youtube#videoListResponse",
"etag": "\"SJZWTG6xR0eGuCOh2bX6w3s4F94/VOhpy08pTLV0gkKEHqgFjpTWvRY\"",
"pageInfo": {
    "totalResults": 1,
    "resultsPerPage": 1
},
"items": [{
    "kind": "youtube#video",
    "etag": "\"SJZWTG6xR0eGuCOh2bX6w3s4F94/zatyJpHwm5XYTpovyREQKk3FNh0\"",
    "id": "7nwwdhZzVro",
    "contentDetails": {
        "duration": "PT5M46S",
        "dimension": "2d",
        "definition": "hd",
        "caption": "false",
        "licensedContent": true,
        "projection": "rectangular"
    },
    "statistics": {
        "viewCount": "261804",
        "likeCount": "3069",
        "dislikeCount": "47",
        "favoriteCount": "0",
        "commentCount": "67"
    }
}]
}

Lets say I have saved the value to a var named String videoDuration, how can I properly format videoDuration to 00:00 or mm:ss? In my case it should show 05:46


Solution

  • In my case android studio gave me a warning: Call requires API level 26 (Current min is 21)

    So I had success with JODA time:

    private String FormatdDate(String time) {
        Period dur = Period.parse(time);
        String strTime;
        if (dur.getHours() > 0) {
            strTime = String.format("%d:%02d:%02d",
                    dur.getHours(),
                    dur.getMinutes(),
                    dur.getSeconds());
        } else {
            strTime = String.format("%02d:%02d",
                    dur.getMinutes(),
                    dur.getSeconds());
        }
        return strTime;
    }