Ruby on Rails - YouTube API - How to Format ISO 8601 Duration (PT45S)

I searched high and low and could not find a direct answer to this. Basically, I call the YouTube API and get a JSON document and then parse it. Everything else is fine, but I don’t understand how to parse the "duration" property to display it as human readable.

The "duration" field appears as "PT1H5M34S" - 1 hour 5 minutes 34 seconds

Or it could be "PT24S" - 24 seconds

Or "PT4M3S" - 4 minutes 3 seconds

There should be a way in Ruby to parse this line and make it readable, so that I can just skip the time on the go in my loop and convert it. Any help or guidance is greatly appreciated. I tried using Date.parse, Time.parse, Date.strptime, as well as many other things ... Like just gsub-out of PT from a string and displaying it, but that doesn't seem right.

+5
source share
2 answers

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

Using:

d = ISO8601::Duration.new('PT1H5M34S') d.to_seconds # => 3934.0 
+7
source

A simple approach to get the number of seconds for videos less than 24 hours:

 dur = "PT34M5S" pattern = "PT" pattern += "%HH" if dur.include? "H" pattern += "%MM" if dur.include? "M" pattern += "%SS" DateTime.strptime(dur, pattern).seconds_since_midnight.to_i 
0
source

Source: https://habr.com/ru/post/1204272/


All Articles