7

How can I parse the youtube duration format which I believe is ISO 8601

This request

https://www.googleapis.com/youtube/v3/videos?id=Kdgt1ZHkvnM&part=contentDetails&key={API_KEY}

Returns

{
 "kind": "youtube#videoListResponse",
 "etag": "\"QVyS2yjpsZ-tKkk4JvgYeO_YkzY/Do26Zx0a-KfdN4FPvoMAgqiFNRA\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#video",
   "etag": "\"QVyS2yjpsZ-tKkk4JvgYeO_YkzY/yZ-09PZbpkEHSEcQeekJuGOCbJY\"",
   "id": "Kdgt1ZHkvnM",
   "contentDetails": {
    "duration": "PT20M1S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "false",
    "licensedContent": false
   }
  }
 ]
}

Is there a library that parses this format "PT20M1S" for .Net?

ojhawkins
  • 3,200
  • 15
  • 50
  • 67
  • http://stackoverflow.com/questions/22148885/converting-youtube-data-api-v3-video-duration-format-to-seconds-in-javascript-no here its solved – Sandip Jun 25 '14 at 13:27
  • 1
    ... and here is a solution for .NET: http://stackoverflow.com/questions/62804/how-to-convert-iso-8601-duration-to-timespan-in-vb-net – Findus Jun 25 '14 at 13:28
  • @Findus thanks mate, works fine. Strange that it would only exist in the xml namespace... – ojhawkins Jun 25 '14 at 13:34
  • You can see related question. : http://stackoverflow.com/questions/19093071/convert-iso-8601-time-format-into-normal-time-duration – Awesome May 08 '15 at 11:43

1 Answers1

19

Yes, YouTube uses ISO 8601 duration format, for more you can check it here Wiki ISO 8601 duration.

So what you need to do is to use the following code (of course in a proper context, when you will parse the XML), but you can get the idea:

TimeSpan youTubeDuration = XmlConvert.ToTimeSpan("PT20M1S");
Peter Stegnar
  • 12,615
  • 12
  • 62
  • 80
  • Not a problem for the OP, since a YouTube video is unlikely to last months, but those finding this answer by searching for "ISO 8601 duration" should note the problem with months in using `XmlConvert.ToTimeSpan`: https://stackoverflow.com/a/5760821/1536933 – EM0 Dec 03 '18 at 11:33