1

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

F.Mysir
  • 2,838
  • 28
  • 39
  • This might be mighty helpful: [How to format a duration in java? (e.g format H:MM:SS)](https://stackoverflow.com/questions/266825/how-to-format-a-duration-in-java-e-g-format-hmmss). And search for more. – Ole V.V. Mar 07 '20 at 10:45

2 Answers2

3

This seems to follow the iso8601 duration format.

String videoDuration = "PT5M46S";
Duration dur = Duration.parse(videoDuration);
String strTime;
if (dur.toHours() > 0) {
    strTime = String.format("%d:%02d:%02d", 
                        dur.toHours(), 
                        dur.toMinutesPart(), 
                        dur.toSecondsPart());
} else {
    strTime = String.format("%02d:%02d",
                        dur.toMinutesPart(), 
                        dur.toSecondsPart());
}
System.out.println(strTime);

This outputs:

05:46

I would leave the check for the hours because some YouTube videos have more than an hour of duration and this way for PT1H15M2S would output 1:15:02.

Notice that toMinutesPart() and toSecondsPart() are from java 9, if you are still using java 8 you can still use Duration to parse it but you have to check for other ways of formating it.

jeprubio
  • 17,312
  • 5
  • 45
  • 56
0

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;
}
F.Mysir
  • 2,838
  • 28
  • 39