Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - YouTube API - How to format duration ISO 8601 (PT45S)

I've searched high and low and can't seem to find a straight answer on this. Basically, I'm calling the YouTube API and getting a JSON document back, then parsing it. Everything else is good, but I don't understand how to parse the 'duration' property to display it as human readable.

The 'duration' field comes over as 'PT1H5M34S' - 1 hour 5 minutes 34 seconds

Or it could be 'PT24S' - 24 seconds

Or 'PT4M3S' - 4 minutes 3 seconds

There has to be a way in Ruby to parse this string and make it human readable so that I can just pass in the duration on the fly in my loop and convert it. Any help or guidance is greatly appreciated. I've tried using Date.parse, Time.parse, Date.strptime, along with many other things... Like just gsub-ing the PT out of the string and displaying it, but that doesn't seem right.

like image 308
Matthew G Avatar asked Oct 08 '14 16:10

Matthew G


1 Answers

Try arnau's ISO8601 parser (https://github.com/arnau/ISO8601)

Usage:

 d = ISO8601::Duration.new('PT1H5M34S')
 d.to_seconds # => 3934.0
like image 198
jlmcdonald Avatar answered Oct 27 '22 00:10

jlmcdonald