Parsing YouTube Durations in .NET

This took me longer than it should have to figure out.

First of all YouTube’s API is available via NuGet prerelease here: https://www.nuget.org/packages?q=Google.Apis.youtube&prerelease=true&sortOrder=relevance I tried just searching via the VS GUI but the “GData” ones are old and not supported anymore.

The documentation is decent but it took me a little while to wrap my head around how the queries work. https://developers.google.com/youtube/v3/docs/videos#resource

The length of the video. The tag value is an ISO 8601 duration in the format PT#M#S, in which the letters PT indicate that the value specifies a period of time, and the letters M and S refer to length in minutes and seconds, respectively. The # characters preceding the M and S letters are both integers that specify the number of minutes (or seconds) of the video. For example, a value of PT15M51S indicates that the video is 15 minutes and 51 seconds long.

If you try to do TimeSpan.Parse on that it doesn’t work. I to do XmlConvert.ToTimeSpan instead. Hattip to this Stack Overflow answer: http://stackoverflow.com/questions/12466188/how-do-i-convert-an-iso8601-timespan-to-a-c-sharp-timespan

Published